結果
問題 |
No.1928 Make a Binary Tree
|
ユーザー |
![]() |
提出日時 | 2025-06-12 20:03:03 |
言語 | PyPy3 (7.3.15) |
結果 |
WA
|
実行時間 | - |
コード長 | 2,258 bytes |
コンパイル時間 | 214 ms |
コンパイル使用メモリ | 82,176 KB |
実行使用メモリ | 125,336 KB |
最終ジャッジ日時 | 2025-06-12 20:08:10 |
合計ジャッジ時間 | 11,811 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 4 WA * 29 TLE * 1 -- * 23 |
ソースコード
from collections import deque import sys def main(): sys.setrecursionlimit(1 << 25) n = int(sys.stdin.readline()) if n == 1: print(1) return 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) depth = [0] * (n + 1) visited = [False] * (n + 1) q = deque([1]) visited[1] = True parent[1] = None while q: u = q.popleft() for v in adj[u]: if not visited[v] and v != parent[u]: parent[v] = u depth[v] = depth[u] + 1 visited[v] = True q.append(v) # Sort nodes excluding root (1) in decreasing order of depth nodes = [i for i in range(2, n + 1)] nodes.sort(key=lambda x: -depth[x]) up = [0] * (n + 1) for u in range(1, n + 1): up[u] = u children = [0] * (n + 1) count = 1 # root is always present for v in nodes: u = parent[v] assigned = False while u is not None: current_up = up[u] # Find the first available ancestor while current_up is not None and children[current_up] >= 2: # Move up to parent's up next_up = parent[current_up] if next_up is None: up[u] = None current_up = None else: up[u] = up[next_up] current_up = up[u] if current_up is not None and children[current_up] < 2: children[current_up] += 1 if children[current_up] == 2: # Update up[u] to the next available ancestor of current_up's parent next_parent = parent[current_up] if next_parent is None: up[u] = None else: up[u] = up[next_parent] assigned = True break else: # Move up to parent of u u = parent[u] if assigned: count += 1 print(count) if __name__ == "__main__": main()