#P10522. Reconstruct House Height Order
Reconstruct House Height Order
Reconstruct House Height Order
There are n houses located along Wutong Road, numbered from south to north as 1, 2, …, n. All houses have distinct heights. LNC starts from the south and climbs the roof of each house in order. When he reaches the top of the i-th house, he looks back at all the houses he has visited so far (i.e. houses 1 to i-1) and among those that are lower in height than the current house, he records the index of the one with the highest height. This index is denoted by ai. In the special case when there is no house with lower height than the current one, we define ai = 0.
Given the sequence a1, a2, …, an (note that for the first house, a1=0 always), your task is to restore the relative ordering of the houses by height. Since the actual height values are unknown, you only need to output the house indices sorted from the lowest house (smallest height) to the highest (largest height).
It is guaranteed that for any legal input there is a unique solution.
The relationship described in the problem can be formally stated using the following property: for every house i (with i > 1), if ai>0, then in the list of houses visited so far (houses 1, 2, …, i-1) the house ai is the one with the maximum height among all houses with height less than house i. In other words, if the visited houses are arranged in increasing order of height, then house i should be inserted immediately after house ai. In case ai = 0, the current house i has a height lower than every previously visited house, so it will become the new smallest.
The solution can be obtained by simulating the visit from south to north and maintaining a list of houses (their indices) in increasing order of height. For each new house i:
- If ai = 0, insert house i at the beginning of the list.
- If ai ≠ 0, find the position of ai in the list and insert house i right after it.
The final list will be the required order of houses from lowest to highest.
inputFormat
The first line of input contains an integer n (1 ≤ n ≤ N), representing the number of houses. The second line contains n space-separated integers a1, a2, …, an, where for each i (1 ≤ i ≤ n), ai = 0 or 1 ≤ ai < i.
outputFormat
Output a single line with n space-separated integers representing the indices of the houses sorted from the lowest to the highest.
sample
1
0
1