Tree Reconstruction (Codeforces 1041E)
Tags: Greedy, data structures

Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.

Input: The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree.Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i < b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.

Output: If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge.Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.

Note: Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.   

Sample Inputs:
4
3 4
1 4
3 4

3
1 3
1 3

3
1 2
2 3

Sample Outputs:
YES
1 3
3 2
2 4

NO

NO

Solution (Python):
n = int(input())
t = n - 1
d = {i: 0 for i in range(1, n + 1)}
comp = []
while t:
    (c1, c2) = map(int, input().split())
    (c1, c2) = (min(c1, c2), max(c1, c2))
    if c2 != n:
        print('NO')
        exit()
    d[c1] += 1
    t = t - 1
p = 0
for c1 in range(1, n):
    p += d[c1]
    if p > c1:
        print('NO')
        exit()
paths = []
for i in d:
    if d[i] != 0:
        path = [n] + [0] * (d[i] - 1) + [i]
        paths.append(path)
l = len(paths)
fill = []
for i in d:
    if d[i] == 0:
        fill.append(i)
ind = 0
for i in range(len(paths)):
    for j in range(len(paths[i])):
        if paths[i][j] == 0:
            paths[i][j] = fill[ind]
            ind = ind + 1
print('YES')
for i in paths:
    for j in range(1, len(i)):
        print(i[j - 1], i[j])

Solution (Python):
def solve():
    n = int(input())
    d = {}
    for _ in range(n - 1):
        (u, v) = map(int, input().split())
        min_ = min(u, v)
        max_ = max(u, v)
        if max_ != n:
            return (False, None)
        if min_ not in d:
            d[min_] = 0
        d[min_] += 1
    if sum(list(d.values())) + 1 != n:
        return (False, None)
    edge = []
    used = {i: False for i in range(1, n + 1)}
    for k in sorted(list(d.keys())):
        used[k] = True
        mid = [n]
        for i in range(k - 1, 0, -1):
            if len(mid) == d[k]:
                break
            if used[i] == False:
                used[i] = True
                mid.append(i)
        if len(mid) < d[k]:
            return (False, None)
        mid.append(k)
        for (u, v) in zip(mid[:-1], mid[1:]):
            edge.append([u, v])
    return (True, edge)
(ans, arr) = solve()
if ans == False:
    print('NO')
else:
    print('YES')
    for (u, v) in arr:
        print(str(u) + ' ' + str(v))

Solution (Python):
from sys import stdin

def bad():
    print('NO')
    exit()
all_in = stdin.readlines()
n = int(all_in[0])
pair = list(map(lambda x: tuple(map(int, x.split())), all_in[1:]))
f = True
for i in range(n - 1):
    if pair[i][0] == n - 1:
        f = False
    if pair[i][1] != n:
        bad()
if f:
    bad()
pair.sort(key=lambda x: x[0])
p = list(map(lambda x: x[0], pair))
ans = [0 for i in range(n)]
st = set(range(1, n))
ans[0] = p[0]
st.remove(p[0])
(a, b) = (0, p[0])
for i in range(1, n - 1):
    (a, b) = (b, p[i])
    if b != a:
        ans[i] = b
        st.remove(b)
ans[-1] = n
max_ = 0
for i in range(n):
    el = ans[i]
    max_ = max(max_, el)
    if not el:
        m = min(st)
        if m > max_:
            bad()
        ans[i] = m
        st.remove(m)
print('YES')
print('\n'.join(map(lambda i: f'{ans[i - 1]} {ans[i]}', range(1, n))))