Terminal Sequence
InterviewTime limit2sMemory limit1024 MB
Given the Prufer-style removal sequence of a labeled tree, reconstruct all N-1 edges and print them in sorted order.
- Level
Medium5 of 10
- Topics
- Tree, Implementation, Greedy, Heap
- Solved
- No attempts yet
Problem
There is a tree with vertices. Each vertex has a distinct number from to . We want to represent this tree as a sequence, as follows.
- Among the leaf vertices of the tree, remove the one with the smallest number. Then append to the sequence the number of the vertex that was connected to it.
- Repeat step 1 until only one edge remains.
For example, suppose the tree has edges , , , , , , , , . The vertices are removed in the order , so the sequence is .
A tree is uniquely determined by such a sequence. Given the sequence described above, find all edges of the tree.
Input
The first line gives the number of vertices . The second line gives the integers that form the sequence. The input is always such that a tree can be built from it.
Output
Print all edges of the tree, one per line. For each edge, print the vertex with the smaller number first. Print the edges in nondecreasing order of the first number, and if the first numbers are equal, in ascending order of the second number.