結果

問題 No.1418 Sum of Sum of Subtree Size
ユーザー raven7959
提出日時 2021-09-25 07:21:19
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 717 ms / 2,000 ms
コード長 769 bytes
コンパイル時間 201 ms
コンパイル使用メモリ 82,652 KB
実行使用メモリ 273,408 KB
最終ジャッジ日時 2024-07-05 11:58:58
合計ジャッジ時間 9,701 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 41
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
sys.setrecursionlimit(10**9)
N=int(input())
G=[[] for _ in range(N)]
for _ in range(N-1):
  a,b=map(lambda x:int(x)-1,input().split())
  G[a].append(b)
  G[b].append(a)
subtree_size=[1]*N
subtree_size_of_childlen=[[] for _ in range(N)]
def dfs(G,v,p=-1):
  for nextv in G[v]:
    if nextv!=p:
      dfs(G,nextv,v)
  for c in G[v]:
    if c!=p:
      subtree_size[v]+=subtree_size[c]
def dfs2(G,v,p=-1):
  for nextv in G[v]:
    if nextv!=p:
      dfs2(G,nextv,v)
  for c in G[v]:
    if c!=p:
      subtree_size_of_childlen[v].append(subtree_size[c])
dfs(G,0)
dfs2(G,0)
ans=0
for i in range(N):
  # print(i)
  ans+=(N-subtree_size[i])*subtree_size[i]
  # print(ans)
  for num in subtree_size_of_childlen[i]:
    ans+=(N-num)*num
  # print(ans)
print(ans+N*N)
0