#P5754. Lexicographical Ranking Assignment
Lexicographical Ranking Assignment
Lexicographical Ranking Assignment
There are N students numbered from 1 to N. You are given a sequence A of length N, where for each student i (1 ≤ i ≤ N), if Ai ≠ 0 then student i has a lower score (or, equivalently, a worse rank) than student Ai. In other words, if Ai ≠ 0 then the rank of student i must be strictly greater than the rank of student Ai (recall that a better rank is represented by a smaller number). If Ai = 0, there is no information regarding student i.
Your task is to assign a rank to every student – that is, produce a permutation H of {1, 2, …, N} – such that for every i with Ai ≠ 0 it holds that
You need to find two rankings:
- H: the lexicographically smallest ranking among all valid rankings.
- X: the lexicographically largest ranking among all valid rankings.
A ranking R = (R[1], R[2], …, R[N]) is lexicographically smaller than another ranking S = (S[1], S[2], …, S[N]) if for some k (1 ≤ k ≤ N) we have R[1] = S[1], R[2] = S[2], …, R[k-1] = S[k-1] and R[k] < S[k].
Hint: The condition H[i] > H[Ai] for all applicable i means that if you view an edge from A[i] to i (whenever A[i] ≠ 0) the ranking ordering of students must be consistent with these precedence constraints. One way to satisfy these is to compute topological orders of the dependency graph. To obtain the lexicographically smallest (or largest) ranking H (when H is considered as an array where the i-th element is the rank of student i), note that if a student appears earlier in the topological order then he gets a smaller ranking number (since we assign ranks in increasing order). Thus, if you always choose the available student with the smallest index when constructing a topological order, you get one valid ranking. Similarly, choosing the available student with the largest index produces the lexicographically largest ranking.
inputFormat
The input consists of two lines. The first line contains a single integer N (the number of students). The second line contains N integers: A1, A2, …, AN, where 0 ≤ Ai ≤ N and if Ai ≠ 0 then student i's rank must be strictly greater than the rank of student Ai.
outputFormat
Output two lines:
- The first line contains N integers representing the lexicographically smallest valid ranking H for students 1 to N.
- The second line contains N integers representing the lexicographically largest valid ranking X for students 1 to N.
Both H and X are permutations of {1, 2, …, N} and satisfy for each i with Ai ≠ 0 the inequality
$$H[i] > H[A_i] \quad \text{and} \quad X[i] > X[A_i]. $$sample
3
0 0 0
1 2 3
3 2 1
</p>