結果

問題 No.1928 Make a Binary Tree
ユーザー lam6er
提出日時 2025-04-16 15:57:34
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 1,568 bytes
コンパイル時間 377 ms
コンパイル使用メモリ 81,392 KB
実行使用メモリ 141,424 KB
最終ジャッジ日時 2025-04-16 16:00:24
合計ジャッジ時間 10,636 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 5 WA * 28 TLE * 1 -- * 23
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from collections import deque

def main():
    n = int(sys.stdin.readline())
    adj = [[] for _ in range(n + 1)]
    for _ in range(n - 1):
        x, y = map(int, sys.stdin.readline().split())
        adj[x].append(y)
        adj[y].append(x)
    
    parent = [0] * (n + 1)
    children = [[] for _ in range(n + 1)]
    visited = [False] * (n + 1)
    q = deque([1])
    visited[1] = True
    parent[1] = -1  # Mark root's parent as -1 to avoid None
    
    bfs_order = []
    while q:
        u = q.popleft()
        for v in adj[u]:
            if not visited[v] and v != parent[u]:
                visited[v] = True
                parent[v] = u
                children[u].append(v)
                q.append(v)
                bfs_order.append(v)
    
    child_count = [0] * (n + 1)
    alive = [True] * (n + 1)
    total = 1  # root is always present
    
    for node in bfs_order:
        if not alive[node]:
            continue
        
        current = parent[node]
        while current != -1 and child_count[current] >= 2:
            current = parent[current]
        
        if current != -1:
            child_count[current] += 1
            total += 1
        else:
            # Mark the subtree rooted at 'node' as dead
            dq = deque([node])
            while dq:
                u = dq.popleft()
                if not alive[u]:
                    continue
                alive[u] = False
                for v in children[u]:
                    dq.append(v)
    
    print(total)

if __name__ == "__main__":
    main()
0