Tree Compass (Codeforces 1944E)
Tags: Greedy, trees

You are given a tree with $$$n$$$ vertices numbered $$$1, 2, \ldots, n$$$. Initially, all vertices are colored white.You can perform the following two-step operation:   Choose a vertex $$$v$$$ ($$$1 \leq v \leq n$$$) and a distance $$$d$$$ ($$$0 \leq d \leq n-1$$$).  For all vertices $$$u$$$ ($$$1 \leq u \leq n$$$) such that $$$\text{dist}^\dagger(u,v)=d$$$, color $$$u$$$ black. Construct a sequence of operations to color all the nodes in the tree black using the minimum possible number of operations. It can be proven that it is always possible to do so using at most $$$n$$$ operations.$$$^\dagger$$$ $$$\text{dist}(x, y)$$$ denotes the number of edges on the (unique) simple path between vertices $$$x$$$ and $$$y$$$ on the tree.

Input: Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 200$$$) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^3$$$) — the number of vertices of the tree.The following $$$n - 1$$$ lines of each test case describe the edges of the tree. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \neq v_i$$$), the indices of the vertices connected by the $$$i$$$-th edge.It is guaranteed that the given edges form a tree.It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^3$$$.

Output: For each test case, first output a single integer $$$op$$$ $$$(1 \le op \le n)$$$, the minimum number of operations needed to color all vertices of the tree black.Then, output $$$op$$$ lines, each containing $$$2$$$ integers. The $$$i$$$-th line should contain the values of $$$v$$$ and $$$d$$$ chosen for the $$$i$$$-th operation ($$$1 \le v \le n$$$, $$$0 \le d \le n - 1$$$)You must guarantee that at the end of $$$op$$$ operations, all vertices are colored black.If there are multiple solutions, you may output any one of them.

Note: In the first test case, there is only one possible operation, and performing it gives us a valid answer.In the second test case, the first operation colors vertex $$$2$$$ black, and the second operation colors vertex $$$1$$$ black. It can be shown that it is impossible to color both vertices black in one operation, so the minimum number of operations needed is $$$2$$$. Another possible solution is to use the $$$2$$$ operations: $$$(u, r) = (1, 0)$$$ and $$$(u, r) = (2, 0)$$$.In the third test case, the first operation colors vertices $$$2$$$, $$$3$$$ and $$$4$$$ black, and the second operation colors vertex $$$1$$$ black. Again, it can be shown that it is impossible to color all vertices black in $$$1$$$ operation, so the minimum number of operations needed is $$$2$$$.In the fourth test case, the first operation colors vertices $$$4$$$, $$$1$$$ and $$$7$$$ black, the second operation colors vertices $$$2$$$, $$$5$$$ and $$$6$$$ black while the third operation colors vertices $$$3$$$ and $$$7$$$ black. Notice that it is allowed to color vertex $$$7$$$ black twice.Thus, each node was marked at least once, with node $$$7$$$ marked twice. It can be shown that it is impossible to color all vertices black in fewer than $$$3$$$ moves.

Sample Inputs:
4
1
2
1 2
4
1 2
1 3
1 4
7
2 7
3 2
6 4
5 7
1 6
6 7

Sample Outputs:
1
1 0
2
1 1
2 1
2
1 1
2 1
3
6 1
7 1
2 1

Solution (Python):
for _ in range(int(input())):
    n = int(input())
    adj = [set() for _ in range(n)]
    deg = [0] * n
    for _ in range(n - 1):
        (u, v) = map(int, input().split())
        u -= 1
        v -= 1
        adj[u].add(v)
        adj[v].add(u)
        deg[u] += 1
        deg[v] += 1
    leaves = list(filter(lambda x: deg[x] <= 1, [i for i in range(n)]))
    cnt = n
    rad = 0
    while cnt > 2:
        cnt -= len(leaves)
        rad += 1
        nls = []
        for u in leaves:
            v = min(adj[u])
            adj[v].remove(u)
            deg[v] -= 1
            if deg[v] == 1:
                nls.append(v)
        leaves = nls
    if cnt == 1:
        print(rad + 1)
        for i in range(rad + 1):
            print(leaves[0] + 1, i)
    elif rad % 2:
        print(rad + 1)
        for i in range(1, rad + 2, 2):
            print(leaves[0] + 1, i)
            print(leaves[1] + 1, i)
    else:
        print(rad + 2)
        for i in range(rad + 2):
            print(leaves[0] + 1, i)

Solution (Python):
import sys, math
input = sys.stdin.readline
out = []

def farthestNode(node, Adj, prev):
    best = node
    bestD = 0
    for u in Adj[node]:
        if u != prev:
            (n, d) = farthestNode(u, Adj, node)
            d += 1
            if d > bestD:
                best = n
                bestD = d
    return (best, bestD)

def dm(Adj):
    """"""
    (farthest, _) = farthestNode(0, Adj, -1)
    (other, d) = farthestNode(farthest, Adj, -1)
    return (farthest, other, d + 1)

def dfs(node, Adj, prev, dist, A):
    if dist == 0:
        A.append(node)
    else:
        for u in Adj[node]:
            if u != prev:
                dfs(u, Adj, node, dist - 1, A)
for t in range(int(input())):
    n = int(input())
    Adj = [[] for _ in range(n)]
    for _ in range(n - 1):
        (a, b) = map(int, input().split())
        Adj[a - 1].append(b - 1)
        Adj[b - 1].append(a - 1)
    (a, b, d) = dm(Adj)
    if d % 4 == 0:
        out.append(str(d // 2))
        A = []
        B = []
        dfs(a, Adj, -1, d // 2, A)
        dfs(b, Adj, -1, d // 2 - 1, B)
        lNodes = set(map(str, A))
        rNodes = set(map(str, B))
        for node in lNodes:
            if node in rNodes:
                left = int(node)
                break
        A = []
        B = []
        dfs(a, Adj, -1, d // 2 - 1, A)
        dfs(b, Adj, -1, d // 2, B)
        lNodes = set(map(str, A))
        rNodes = set(map(str, B))
        for node in lNodes:
            if node in rNodes:
                right = int(node)
                break
        for i in range(1, d // 2, 2):
            out.append(str(left + 1) + ' ' + str(i))
            out.append(str(right + 1) + ' ' + str(i))
    else:
        out.append(str(d // 2 + 1))
        A = []
        B = []
        if d % 2 == 0:
            dfs(a, Adj, -1, d // 2 - 1, A)
            dfs(b, Adj, -1, d // 2, B)
        else:
            dfs(a, Adj, -1, d // 2, A)
            dfs(b, Adj, -1, d // 2, B)
        lNodes = set(map(str, A))
        rNodes = set(map(str, B))
        for node in lNodes:
            if node in rNodes:
                center = int(node)
                break
        for i in range(0, d // 2 + 1):
            out.append(str(center + 1) + ' ' + str(i))
print('\n'.join(out))

Solution (Python):
import sys, math
input = sys.stdin.readline
out = []

def farthestNode(node, Adj, prev):
    best = node
    bestD = 0
    for u in Adj[node]:
        if u != prev:
            (n, d) = farthestNode(u, Adj, node)
            d += 1
            if d > bestD:
                best = n
                bestD = d
    return (best, bestD)

def dm(Adj):
    """"""
    (farthest, _) = farthestNode(0, Adj, -1)
    (other, d) = farthestNode(farthest, Adj, -1)
    return (farthest, other, d + 1)

def dfs(node, Adj, prev, dist, A):
    if dist == 0:
        A.append(node)
    else:
        for u in Adj[node]:
            if u != prev:
                dfs(u, Adj, node, dist - 1, A)
for t in range(int(input())):
    n = int(input())
    Adj = [[] for _ in range(n)]
    for _ in range(n - 1):
        (a, b) = map(int, input().split())
        Adj[a - 1].append(b - 1)
        Adj[b - 1].append(a - 1)
    (a, b, d) = dm(Adj)
    if d % 4 == 0:
        out.append(str(d // 2))
        A = []
        B = []
        dfs(a, Adj, -1, d // 2, A)
        dfs(b, Adj, -1, d // 2 - 1, B)
        lNodes = set(map(str, A))
        rNodes = set(map(str, B))
        for node in lNodes:
            if node in rNodes:
                left = int(node)
                break
        A = []
        B = []
        dfs(a, Adj, -1, d // 2 - 1, A)
        dfs(b, Adj, -1, d // 2, B)
        lNodes = set(map(str, A))
        rNodes = set(map(str, B))
        for node in lNodes:
            if node in rNodes:
                right = int(node)
                break
        for i in range(1, d // 2, 2):
            out.append(str(left + 1) + ' ' + str(i))
            out.append(str(right + 1) + ' ' + str(i))
    else:
        out.append(str(d // 2 + 1))
        A = []
        B = []
        if d % 2 == 0:
            dfs(a, Adj, -1, d // 2 - 1, A)
            dfs(b, Adj, -1, d // 2, B)
        else:
            dfs(a, Adj, -1, d // 2, A)
            dfs(b, Adj, -1, d // 2, B)
        lNodes = set(map(str, A))
        rNodes = set(map(str, B))
        for node in lNodes:
            if node in rNodes:
                center = int(node)
                break
        for i in range(0, d // 2 + 1):
            out.append(str(center + 1) + ' ' + str(i))
print('\n'.join(out))