Tree Compass (Codeforces 1943C)
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):
def argmax(l):
    return max(range(len(l)), key=lambda x: l[x])

def alg():
    n = int(input())
    u2vs = [[] for _ in range(n)]
    for _ in range(n - 1):
        (u, v) = tuple(map(int, input().split()))
        u -= 1
        v -= 1
        u2vs[u].append(v)
        u2vs[v].append(u)

    def bfs(s):
        nonlocal n
        d = [-1 for _ in range(n)]
        prev = [-1 for _ in range(n)]
        q = [s]
        d[s] = 0
        while len(q) > 0:
            u = q.pop(0)
            du = d[u]
            for v in u2vs[u]:
                if d[v] == -1:
                    d[v] = du + 1
                    prev[v] = u
                    q.append(v)
        return (d, prev)
    (d, _) = bfs(0)
    a = argmax(d)
    (d, previous) = bfs(a)
    b = argmax(d)
    path_ba = [b]
    while True:
        n = previous[path_ba[-1]]
        if n == -1:
            break
        path_ba.append(n)
    ops = []
    if len(path_ba) % 2 == 1:
        ci = len(path_ba) // 2
        c = path_ba[ci]
        for i in range(ci + 1):
            ops.append((c, i))
    else:
        ci2 = len(path_ba) // 2
        ci1 = ci2 - 1
        c1 = path_ba[ci1]
        c2 = path_ba[ci2]
        for i in range(1, len(path_ba) - ci1, 2):
            ops.append((c1, i))
            ops.append((c2, i))
    print(len(ops))
    print(*map(lambda x: f'{x[0] + 1} {x[1]}', ops), sep='\n')
    return None
if __name__ == '__main__':
    for _ in range(int(input())):
        alg()

Solution (Python):
def dfs(v, gr, used):
    used[v] = 1
    for i in gr[v]:
        if used[i] == 0:
            dfs(i, gr, used)
    return 0

def find_center(gr, depth, color):
    leaves = []
    for i in range(len(gr)):
        if len(gr[i]) == 1:
            leaves.append(i)
    for i in leaves:
        q = []
        for k in gr[i]:
            q.append(k)
        gr[i].remove(q[0])
        gr[q[0]].remove(i)
        depth[k] = color + 1
    newl = 0
    vert = 0
    for i in range(len(gr)):
        if len(gr[i]) > 0:
            vert += 1
        if len(gr[i]) == 1:
            newl += 1
    if newl <= 2 and vert <= 2:
        return 0
    else:
        find_center(gr, depth, color + 1)
        return 0

def solve_3():
    n = int(input())
    a = [set() for i in range(n)]
    for i in range(n - 1):
        (u, v) = [int(z) - 1 for z in input().split()]
        a[u].add(v)
        a[v].add(u)
    depth = [0] * n
    color = 0
    if n == 1:
        print(1)
        print('1 0')
        return
    if n == 2:
        print(2)
        print('1 1\n2 1')
        return
    find_center(a, depth, color)
    rad = max(depth)
    centres = depth.count(rad)
    if centres == 1:
        print(rad + 1)
        sqrt = depth.index(rad)
        for i in range(rad + 1):
            print(sqrt + 1, i)
    elif rad % 2 == 1:
        sqrt1 = depth.index(rad)
        depth.reverse()
        sqrt2 = n - 1 - depth.index(rad)
        print(1 + rad)
        for i in range(1, rad + 2, 2):
            print(sqrt1 + 1, i)
            print(sqrt2 + 1, i)
    else:
        print(rad + 2)
        sqrt1 = depth.index(rad)
        for i in range(rad + 2):
            print(sqrt1 + 1, i)
t = int(input())
for i in range(t):
    solve_3()

Solution (Python):
from sys import stdin
input = lambda : stdin.readline()[:-1]

def dfs(roots):
    dist = [-1] * n
    todo = []
    for r in roots:
        todo.append(r)
        dist[r] = 0
    while todo:
        v = todo.pop()
        for u in edge[v]:
            if dist[u] == -1:
                dist[u] = dist[v] + 1
                todo.append(u)
    return dist
for _ in range(int(input())):
    n = int(input())
    edge = [[] for i in range(n)]
    for i in range(n - 1):
        (a, b) = map(lambda x: int(x) - 1, input().split())
        edge[a].append(b)
        edge[b].append(a)
    dist0 = dfs([0])
    mx = max(dist0)
    v1 = dist0.index(mx)
    dist1 = dfs([v1])
    mx = max(dist1)
    v2 = dist1.index(mx)
    dist2 = dfs([v2])
    if mx % 2 == 0:
        d = mx // 2
        for i in range(n):
            if dist1[i] == dist2[i] == d:
                mid = i
        print(d + 1)
        for i in range(d + 1):
            print(mid + 1, i)
    else:
        mids = []
        for i in range(n):
            if dist1[i] >= mx // 2 and dist2[i] >= mx // 2 and (dist1[i] + dist2[i] == mx):
                mids.append(i)
        assert len(mids) == 2
        ans = []
        for mid in mids:
            D = dfs([mid])
            mx = max(D)
            for i in range(mx + 1):
                if i % 2 == 1:
                    ans.append([mid, i])
        print(len(ans))
        for (x, y) in ans:
            print(x + 1, y)