Ghost Leg
InterviewTime limit1sMemory limit1024 MB
Simulate a Ghost Leg with n vertical lines and m horizontal lines from top to bottom, then print the resulting order of the elements.
- Level
Easy2 of 10
- Topics
- Simulation, Array
- Solved
- No attempts yet
Problem
A Ghost Leg is a method for representing permutations.
A Ghost Leg is drawn as a set of vertical lines, one for each element being permuted. Horizontal lines connect adjacent vertical lines, and no two horizontal lines share an endpoint. The illustration to the right shows an example.
To find where an element ends up, start at the top of its vertical line. Move down until you reach the first horizontal line touching that line, then follow it to the adjacent vertical line. It does not matter whether the line goes left or right. Keep moving down and following horizontal lines until you reach the bottom. That bottom position is the element's final position.
In the example, element 2 ends up third. The red dotted lines show its path. Element 1 ends up fourth, element 3 ends up first, and element 4 ends up second.
Given a Ghost Leg, find the resulting permutation. Apply the permutation and print the elements in their new order.
Input
The first line contains two positive integers () and (). Here is the number of elements being permuted, and is the number of horizontal lines. The vertical lines are numbered from 1 to from left to right.
Each of the next lines contains one integer (). This means there is a horizontal line between vertical lines and . The lines are listed from top to bottom. No two horizontal lines are at the same height.
Output
Print lines, each containing one integer. The first line is the element that ends up first in the permutation, the second line is the element that ends up second, and so on through the th line.