結果

問題 No.1928 Make a Binary Tree
ユーザー harurunharurun
提出日時 2021-12-15 20:59:52
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,182 ms / 3,000 ms
コード長 1,064 bytes
コンパイル時間 302 ms
コンパイル使用メモリ 82,492 KB
実行使用メモリ 415,552 KB
最終ジャッジ日時 2024-11-06 04:27:49
合計ジャッジ時間 34,013 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 57
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque
from heapq import *
from sys import setrecursionlimit
setrecursionlimit(400010)

def main():
  N=int(input())
  Graph=[[]for i in range(N)]
  for i in range(N-1):
    x,y=map(int,input().split())
    Graph[x-1].append(y-1)
    Graph[y-1].append(x-1)
  checked=[False]*N
  vec=[[]for i in range(N)]
  def dfs(i,parent):
    checked[i]=True
    for to in Graph[i]:
      if not checked[to]:
        p=dfs(to,i)
        heappush(vec[i],-p)
    max_size=len(vec[i])
    index=i
    for to in Graph[i]:
      if to!=parent and len(vec[to])>max_size:
        index=to
        max_size=len(vec[to])
    if index!=i:
      while vec[i]:
        heappush(vec[index],heappop(vec[i]))
    for to in Graph[i]:
      if index!=to and to!=parent:
        while vec[to]:
          heappush(vec[index],heappop(vec[to]))
    vec[i]=vec[index]
    res=1
    if len(vec[i])<=2:
      while vec[i]:
        res+=-heappop(vec[i])
    else:
      for j in range(2):
        res+=-heappop(vec[i])
    return res
  ans=dfs(0,-1)
  print(ans)
  return

main()
0