結果

問題 No.1928 Make a Binary Tree
ユーザー lam6er
提出日時 2025-04-15 22:27:19
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 1,952 bytes
コンパイル時間 220 ms
コンパイル使用メモリ 82,036 KB
実行使用メモリ 848,576 KB
最終ジャッジ日時 2025-04-15 22:30:04
合計ジャッジ時間 27,450 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 3 WA * 32 MLE * 12 -- * 10
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque

def main():
    import sys
    input = sys.stdin.read
    data = input().split()
    idx = 0
    n = int(data[idx])
    idx += 1
    
    adj = [[] for _ in range(n + 1)]
    for _ in range(n - 1):
        x = int(data[idx])
        y = int(data[idx + 1])
        adj[x].append(y)
        adj[y].append(x)
        idx += 2
    
    parent = [0] * (n + 1)
    children = [[] for _ in range(n + 1)]
    visited = [False] * (n + 1)
    q = deque([1])
    visited[1] = True
    
    while q:
        u = q.popleft()
        for v in adj[u]:
            if not visited[v] and v != parent[u]:
                parent[v] = u
                children[u].append(v)
                visited[v] = True
                q.append(v)
    
    post_order = []
    stack = [(1, False)]
    visited = [False] * (n + 1)
    
    while stack:
        u, processed = stack.pop()
        if processed:
            post_order.append(u)
            continue
        visited[u] = True
        stack.append((u, True))
        for v in reversed(children[u]):
            stack.append((v, False))
    
    dp = [0] * (n + 1)
    max1 = [0] * (n + 1)
    max2 = [0] * (n + 1)
    
    for u in post_order:
        child_top1 = 0
        child_top2 = 0
        for v in children[u]:
            if max1[v] > child_top1:
                child_top2 = child_top1
                child_top1 = max1[v]
            elif max1[v] > child_top2:
                child_top2 = max1[v]
            if max2[v] > child_top1:
                child_top2 = child_top1
                child_top1 = max2[v]
            elif max2[v] > child_top2:
                child_top2 = max2[v]
        dp[u] = 1 + child_top1 + child_top2
        candidates = [child_top1, child_top2, dp[u]]
        candidates.sort(reverse=True)
        max1[u] = candidates[0]
        max2[u] = candidates[1] if len(candidates) >= 2 else 0
    
    print(dp[1])

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