Link Cut Centroids (Codeforces 1406C)
Tags: Others, trees

Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles.A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible.For example, the centroid of the following tree is $$$2$$$, because when you cut it, the size of the largest connected component of the remaining graph is $$$2$$$ and it can't be smaller.  However, in some trees, there might be more than one centroid, for example:  Both vertex $$$1$$$ and vertex $$$2$$$ are centroids because the size of the largest connected component is $$$3$$$ after cutting each of them.Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut.He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists.

Input: The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\leq t\leq 10^4$$$) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer $$$n$$$ ($$$3\leq n\leq 10^5$$$) — the number of vertices.Each of the next $$$n-1$$$ lines contains two integers $$$x, y$$$ ($$$1\leq x,y\leq n$$$). It means, that there exists an edge connecting vertices $$$x$$$ and $$$y$$$.It's guaranteed that the given graph is a tree.It's guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.

Output: For each test case, print two lines.In the first line print two integers $$$x_1, y_1$$$ ($$$1 \leq x_1, y_1 \leq n$$$), which means you cut the edge between vertices $$$x_1$$$ and $$$y_1$$$. There should exist edge connecting vertices $$$x_1$$$ and $$$y_1$$$.In the second line print two integers $$$x_2, y_2$$$ ($$$1 \leq x_2, y_2 \leq n$$$), which means you add the edge between vertices $$$x_2$$$ and $$$y_2$$$.The graph after these two operations should be a tree.If there are multiple solutions you can print any.

Note: Note that you can add the same edge that you cut.In the first test case, after cutting and adding the same edge, the vertex $$$2$$$ is still the only centroid.In the second test case, the vertex $$$2$$$ becomes the only centroid after cutting the edge between vertices $$$1$$$ and $$$3$$$ and adding the edge between vertices $$$2$$$ and $$$3$$$.

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

Sample Outputs:
1 2
1 2
1 3
2 3

Solution (Python):
import threading
import sys
threading.stack_size(16 * 2048 * 2048)
sys.setrecursionlimit(100010)
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def gettot(index, father, neigh, maxindex, maxsubtree):
    n = len(neigh)
    upper = n - 1
    maximum = 0
    for ele in neigh[index]:
        if ele == father:
            continue
        sub = gettot(ele, index, neigh, maxindex, maxsubtree)
        upper -= sub
        if sub > maximum:
            maximum = sub
            maxindex[index] = ele
            maxsubtree[index] = sub
    if upper > maximum:
        maxindex[index] = father
        maxsubtree[index] = upper
    return n - upper

def main():
    T = int(input())
    r = 1
    while r <= T:
        n = int(input())
        neigh = [[] for i in range(n)]
        first = []
        for i in range(n - 1):
            (u, v) = map(int, input().split())
            if not first:
                first.append([u, v])
            neigh[u - 1].append(v - 1)
            neigh[v - 1].append(u - 1)
        maxsubtree = [0] * n
        maxindex = [-1] * n
        visited = [False] * n
        gettot(0, -1, neigh, maxindex, maxsubtree)
        minimum = min(maxsubtree)
        min_index = []
        for i in range(n):
            if maxsubtree[i] == minimum:
                min_index.append(i)
        if len(min_index) == 1:
            print(first[0][0], first[0][1])
            print(first[0][0], first[0][1])
        else:
            a = maxindex[min_index[0]]
            for ele in neigh[a]:
                if ele == min_index[0]:
                    continue
                print(a + 1, ele + 1)
                print(min_index[0] + 1, ele + 1)
                break
        r += 1
threading.Thread(target=main).start()

Solution (Python):
import threading
import sys
threading.stack_size(16 * 2048 * 2048)
sys.setrecursionlimit(100010)
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def gettot(index, father, neigh, maxindex, maxsubtree):
    n = len(neigh)
    upper = n - 1
    maximum = 0
    for ele in neigh[index]:
        if ele == father:
            continue
        sub = gettot(ele, index, neigh, maxindex, maxsubtree)
        upper -= sub
        if sub > maximum:
            maximum = sub
            maxindex[index] = ele
            maxsubtree[index] = sub
    if upper > maximum:
        maxindex[index] = father
        maxsubtree[index] = upper
    return n - upper

def main():
    T = int(input())
    r = 1
    while r <= T:
        n = int(input())
        neigh = [[] for i in range(n)]
        first = []
        for i in range(n - 1):
            (u, v) = map(int, input().split())
            if not first:
                first.append([u, v])
            neigh[u - 1].append(v - 1)
            neigh[v - 1].append(u - 1)
        maxsubtree = [0] * n
        maxindex = [-1] * n
        visited = [False] * n
        gettot(0, -1, neigh, maxindex, maxsubtree)
        minimum = min(maxsubtree)
        min_index = []
        for i in range(n):
            if maxsubtree[i] == minimum:
                min_index.append(i)
        if len(min_index) == 1:
            print(first[0][0], first[0][1])
            print(first[0][0], first[0][1])
        else:
            a = maxindex[min_index[0]]
            for ele in neigh[a]:
                if ele == min_index[0]:
                    continue
                print(a + 1, ele + 1)
                print(min_index[0] + 1, ele + 1)
                break
        r += 1
threading.Thread(target=main).start()

Solution (Python):
import os, sys
from io import BytesIO, IOBase
import copy
from collections import deque, defaultdict
import heapq
import math
import bisect
from itertools import accumulate
import threading
input = lambda : sys.stdin.readline().rstrip('\r\n')
printf = lambda d: sys.stdout.write(str(d) + '\n')
INF = 9999999999999

def read():
    line = sys.stdin.readline().strip()
    while not line:
        line = sys.stdin.readline().strip()
    return map(int, line.split())

def I():
    return int(input())

def dfs(u):
    global f, s, f_min, s_min, n
    vis[u] = True
    maxsize = 0
    size = 1
    for v in t[u]:
        if vis[v]:
            continue
        v_size = dfs(v)
        maxsize = max(maxsize, v_size)
        size += v_size
    tmp = max(maxsize, n - size)
    if tmp < f_min:
        f_min = tmp
        f = u
    elif tmp == f_min:
        s = u
        s_min = tmp
    return size
vis = []
t = []
f = s = 0
f_min = s_min = INF
n = 0

def main():
    global f, s, f_min, s_min, vis, t, n
    for _ in range(I()):
        n = I()
        t = [[] for _ in range(n + 1)]
        for _ in range(n - 1):
            (x, y) = read()
            t[x].append(y)
            t[y].append(x)
        vis = [False] * (n + 1)
        f = s = 0
        f_min = s_min = INF
        dfs(1)
        if f_min != s_min:
            s = 0
            s_min = INF
        if s == 0:
            print(x, y)
            print(x, y)
        else:
            f_leaf = leaf = 0
            q = deque()
            q.append((f, s))
            while q:
                (u, fa) = q.popleft()
                for v in t[u]:
                    if v == fa:
                        continue
                    q.append((v, u))
                    leaf = v
                    f_leaf = u
                    break
            print(f_leaf, leaf)
            print(leaf, s)
max_recur_size = 10 ** 5 * 2 + 1000
max_stack_size = max_recur_size * 500
sys.setrecursionlimit(max_recur_size)
threading.stack_size(max_stack_size)
thread = threading.Thread(target=main)
thread.start()