Robotic Sort
Time limit1sMemory limit128 MB
Simulate a specific selection-sort-by-reversal algorithm on samples with stable tie-breaking and report the position used in each reversal step, requiring an efficient order-statistics data structure for up to 100,000 elements.
- Level
Medium6 of 10
- Topics
- Segment tree, Sorting, Simulation, Binary search
- Solved
- No attempts yet
Problem
Somewhere deep in the buildings of the Czech Technical University there are laboratories for examining the mechanical and electrical properties of various materials. In this task you are to write the software for a robot that handles samples in such a laboratory.
Imagine there are material samples lined up on a running belt. The samples have different heights, which may cause trouble for the next processing unit. To eliminate such trouble, we need to sort the samples by their height into ascending order.
Reordering is done by a mechanical robot arm that can pick up any number of consecutive samples and turn them around, so that their mutual order is reversed. In other words, one robot operation can reverse the order of the samples on the positions between A and B.
One way to sort the samples is the following. First find the position P1 of the smallest sample and reverse the order between positions 1 and P1, which brings the smallest sample to the front. Then find the position P2 of the second smallest sample and reverse the order between positions 2 and P2. Then handle the third sample the same way, and so on.
For example, suppose there are 6 samples. If the smallest one is at the 4th position, the robot arm reverses the first 4 samples. If the second smallest is the last one, the next operation reverses the five samples on positions 2–6. The third step reverses positions 3–4, and so on.
Your task is to find the sequence of reversal operations that sorts the samples using the algorithm above. If several samples have the same height, their mutual order must be preserved: a sample that came earlier in the initial order must also come before the others of the same height in the final order.
Input
The input consists of several scenarios. Each scenario is described by two lines. The first line contains one integer N, the number of samples, 1 ≤ N ≤ 100 000. The second line lists exactly N space-separated positive integers giving the heights of the individual samples in their initial order.
The last scenario is followed by a line containing a single zero.
Output
For each scenario, output one line with exactly N integers P1, P2, …, PN separated by single spaces. Here Pi is the current position, just before the i-th reversal operation, of the sample that ends up at position i in the sorted order (that is, the i-th smallest sample; ties are broken by the initial order). Every Pi satisfies 1 ≤ Pi ≤ N.
If a sample is already at its correct position Pi, you must still output that value Pi, meaning that the "interval between Pi and Pi" (a single sample) is reversed.