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()