結果

問題 No.1418 Sum of Sum of Subtree Size
ユーザー tktk_snsn
提出日時 2021-03-15 20:47:25
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
AC  
実行時間 565 ms / 2,000 ms
コード長 674 bytes
コンパイル時間 149 ms
コンパイル使用メモリ 12,800 KB
実行使用メモリ 30,464 KB
最終ジャッジ日時 2024-11-07 09:31:01
合計ジャッジ時間 11,032 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 41
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)

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

topo = []
par = [-1] * N
q = [0]
while q:
    s = q.pop()
    topo.append(s)
    for t in edge[s]:
        if t == par[s]:
            continue
        par[t] = s
        q.append(t)
        edge[t].remove(s)


ans = N * N
size = [1] * N
for s in topo[::-1]:
    tmp = N - 1
    for c in edge[s]:
        ans += (N - size[c]) * size[c]
        tmp -= size[c]
    ans += size[s] * tmp
    size[par[s]] += size[s]

print(ans)
0