목차

트리 게임

ps
링크acmicpc.net/…
출처BOJ
문제 번호34769
문제명트리 게임
레벨플래티넘 3
분류

게임이론

시간복잡도O(n)
인풋사이즈n<=200,000
사용한 언어Python 3.13
제출기록75040KB / 664ms
최고기록464ms
해결날짜2025/12/28

풀이

코드

"""Solution code for "BOJ 34769. 트리 게임".

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

Tags: [tree]
"""

from teflib import tree as ttree


def main():
    N, tree = ttree.from_input()

    dist_2_node_counts = []
    for neighbors in tree:
        count = 0
        for v in neighbors:
            count += len(tree[v]) - 1
        dist_2_node_counts.append(count)

    answer = (N - 1) * 2
    for u, neighbors in enumerate(tree):
        v_cands = [v for v in neighbors if len(tree[v]) > 1]
        if len(v_cands) > 1:
            continue
        neighbor_v = tree[v_cands[0]]
        if len(neighbor_v) == 2:
            w1, w2 = neighbor_v
            w = w1 + w2 - u
            answer += dist_2_node_counts[w]
        else:
            answer += len(neighbor_v) - 1

    print(answer)


if __name__ == '__main__':
    main()