This page is still under construction.

Parts of this page are still being built. What you see may change.

Constructing a Tree

Time limit2sMemory limit1024 MB

Summary
Given a Prüfer-like sequence produced by always removing the largest leaf, decide whether exactly one tree generates it and print that tree's edges in lexicographic order, else -1.
Level

Medium7 of 10

Topics
Tree, Greedy, Implementation, Heap
Solved
No attempts yet

Problem

There is a tree with N vertices, numbered 1 through N. From this tree we build a sequence of (N-2) positive integers as follows.

  1. Among the vertices of degree 1, pick the one with the largest number. Call this vertex x.
  2. Append to the sequence the number of the vertex adjacent to x.
  3. Delete from the tree the edges incident to x.
  4. Repeat steps 1 through 3 a total of (N-2) times.

Given a sequence {a1, ..., aN-2}, find a tree from which this sequence can be produced by the procedure above.

Input

The input is given as follows.

N
a1 . . . aN-2

Output

If such a tree exists, print its (N-1) edges according to the following rules.

  • Each edge must be printed in the form a b with a < b.
  • The edges must be printed in lexicographic order. That is, for any two edges (a1, b1) and (a2, b2), if a1 < a2, or if a1 = a2 and b1 < b2, then edge (a1, b1) must be printed before edge (a2, b2).

If no tree exists, or if two or more trees exist, print -1.

Constraints

  • 3 ≤ N ≤ 500,000
  • 1 ≤ ai ≤ N (1 ≤ i ≤ N-2)

Examples2

  1. Example 1

    Input
    9
    9 4 4 5 4 4 6
    
    Expected output
    1 6
    2 4
    3 5
    4 5
    4 6
    4 7
    4 9
    8 9
    
  2. Example 2

    Input
    11
    4 3 6 10 2 1 8 9 3
    
    Expected output
    1 3
    1 4
    2 8
    2 10
    3 7
    3 9
    4 11
    5 6
    6 10
    8 9