結果

問題 No.1418 Sum of Sum of Subtree Size
ユーザー H3PO4
提出日時 2022-05-09 13:32:37
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
AC  
実行時間 443 ms / 2,000 ms
コード長 609 bytes
コンパイル時間 97 ms
コンパイル使用メモリ 12,544 KB
実行使用メモリ 38,016 KB
最終ジャッジ日時 2024-07-16 11:56:08
合計ジャッジ時間 9,352 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 41
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from collections import deque

input = sys.stdin.buffer.readline

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

d = deque([(0, -1)])
dfs_order = []

while d:
    v, p = d.pop()
    for x in T[v]:
        if x == p:
            continue
        dfs_order.append((x, v))
        d.append((x, v))

subtree_size = [1] * N

for x, v in reversed(dfs_order):
    subtree_size[v] += subtree_size[x]

ans = N * N
for v in range(N):
    ans += subtree_size[v] * (N - subtree_size[v]) * 2
print(ans)
0