結果

問題 No.1928 Make a Binary Tree
ユーザー tnodinotnodino
提出日時 2022-05-08 14:39:03
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
WA  
実行時間 -
コード長 1,180 bytes
コンパイル時間 185 ms
コンパイル使用メモリ 12,672 KB
実行使用メモリ 108,416 KB
最終ジャッジ日時 2024-07-08 02:36:52
合計ジャッジ時間 41,379 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 33 WA * 24
権限があれば一括ダウンロードができます

ソースコード

diff #

from sys import setrecursionlimit
setrecursionlimit(10**6)

from heapq import heappop,heappush

def dfs(pos, pre):
    global Flg, Vec
    Flg[pos] = True
    for nxt in G[pos]:
        if Flg[nxt]:
            continue
        P = dfs(nxt, pos)
        heappush(Vec[pos], -P)
    M = len(Vec[pos])
    idx = pos
    for nxt in G[pos]:
        if nxt == pre:
            continue
        if len(Vec[nxt]) > M:
            M = len(Vec[nxt])
            idx = nxt
    if idx != pos:
        while Vec[pos]:
            heappush(Vec[idx], heappop(Vec[pos]))
    for nxt in G[pos]:
        if nxt == pre:
            continue
        if nxt == idx:
            continue
        while Vec[nxt]:
            heappush(Vec[pos], heappop(Vec[nxt]))
    Vec[pos] = Vec[idx]
    ret = 1
    if len(Vec[pos]) <= 2:
        while Vec[pos]:
            ret += -heappop(Vec[pos])
    else:
        for _ in range(2):
            ret += -heappop(Vec[pos])
    return ret

N = int(input())
G = [[] for _ in range(N)]
for _ in range(N-1):
    x,y = map(int,input().split())
    x -= 1
    y -= 1
    G[x].append(y)
    G[y].append(x)
Flg = [False] * N
Vec = [[] for _ in range(N)]
print(dfs(0, -1))
0