Skip to content
本站總訪問量
本站訪客數 人次

d459. 一棵小樹

python
n = int(input())
tree = {}
for _ in range(n - 1):
    u, v = input().split()
    if u not in tree:
        tree[u] = []

    if v not in tree:
        tree[v] = []

    tree[u].append(v)
    tree[v].append(u)

dp = [1] * (n + 1)

# print(tree)


def dfs(node, visited=set()):
    visited.add(node)
    if node in tree:
        for child in tree[node]:
            if child not in visited:
                dfs(child, visited)
                dp[int(node)] += dp[int(child)]

dfs('1')

# print(dp)
res = []
for index, item in enumerate(dp):
    if index == 0:
        continue
    print(f"{index:2}-{item:5}")

Contributors

The avatar of contributor named as lucashsu95 lucashsu95

Changelog