#B3630. Reconstruct the Queue
Reconstruct the Queue
Reconstruct the Queue
There are ( n ) children, numbered from ( 1 ) to ( n ) ((2 \le n \le 10^6)). They are arranged in a queue. Each child knows only the number of the child immediately behind him. Each child tells you the number of the child behind him, and you are also given the number of the child at the front of the queue. Your task is to reconstruct the order of the queue from front to back and output the numbers of the children in order.
Example: Suppose the queue order is: 2, 4, 1, 3. Then the child with number 2 says that the next child is 4, the child with number 4 says that the next child is 1, the child with number 1 says that the next child is 3, and the child with number 3 (being the last) has no follower, which is represented as 0.
inputFormat
The first line contains two integers \( n \) and head where \( n \) is the number of children and head is the number of the child at the front of the queue.
The second line contains \( n \) integers. The \( i\)-th integer represents the number of the child immediately behind the child with number \( i \). If a child does not have a follower (i.e. he is the last in the queue), the number will be given as 0.
You can assume that the input always forms a valid queue that includes all \( n \) children.
outputFormat
Output a single line containing the \( n \) numbers representing the order of the children in the queue from front to back, separated by a space.
sample
4 2
3 4 0 1
2 4 1 3
</p>