結果

問題 No.1418 Sum of Sum of Subtree Size
ユーザー AEn
提出日時 2022-12-07 22:47:52
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 757 ms / 2,000 ms
コード長 835 bytes
コンパイル時間 216 ms
コンパイル使用メモリ 82,304 KB
実行使用メモリ 247,296 KB
最終ジャッジ日時 2024-10-14 02:18:06
合計ジャッジ時間 9,731 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 41
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
sys.setrecursionlimit(10**8)

N = int(input())
G = [list() for _ in range(N)]
for i in range(N-1):
    a, b = map(int, input().split())
    a-=1;b-=1
    G[a].append(b)
    G[b].append(a)

sub_tree = [0]*N
def dfs(v,p):
    for next_v in G[v]:
        if next_v == p:
            continue
        dfs(next_v, v)
    sub_tree[v] = 1
    for c in G[v]:
        if c== p:
            continue
        sub_tree[v] += sub_tree[c]

def count(v,p,sm):
    for nex in G[v]:
        if nex==p:continue
        v1, v2 = sub_tree[v], sub_tree[nex]
        sm += v1-2*v2
        sub_tree[v] = v1-v2
        sub_tree[nex] = v1
        global res
        res += sm
        count(nex,v,sm)
        sub_tree[v] = v1
        sub_tree[nex] = v2
        sm -= v1-2*v2
        
dfs(0,-1)
res = sum(sub_tree)
count(0,-1,sum(sub_tree))
print(res)
0