목차

Tree Cutting

ps
링크acmicpc.net/…
출처BOJ
문제 번호7045
문제명Tree Cutting
레벨골드 3
분류

센트로이드

시간복잡도O(n)
인풋사이즈n<=10,000
사용한 언어Python
제출기록35024KB / 168ms
최고기록112ms
해결날짜2022/10/12

풀이

코드

"""Solution code for "BOJ 7045. Tree Cutting".

- Problem link: https://www.acmicpc.net/problem/7045
- Solution link: http://www.teferi.net/ps/problems/boj/7045

Tags: [Centroid]
"""

import sys
from teflib import tree as ttree


def find_centroids(tree):
    sizes = ttree.dp_on_tree(tree, 0, lambda vals, u: sum(vals) + 1)
    half_size = len(tree) // 2
    p, u = -1, 0
    while True:
        c = max((c for c in tree[u] if c != p), key=sizes.__getitem__)
        if sizes[c] == half_size:
            return [u, c]
        elif sizes[c] < half_size:
            return [u]
        p, u = u, c


def main():
    N = int(sys.stdin.readline())
    if N == 1:
        print('1')
        return
    tree = [[] for _ in range(N)]
    for _ in range(N - 1):
        X, Y = [int(x) for x in sys.stdin.readline().split()]
        tree[X - 1].append(Y - 1)
        tree[Y - 1].append(X - 1)
    print(*(u + 1 for u in sorted(find_centroids(tree))), sep='\n')


if __name__ == '__main__':
    main()