結果

問題 No.1418 Sum of Sum of Subtree Size
ユーザー wolgnik
提出日時 2021-03-05 22:10:36
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 182 ms / 2,000 ms
コード長 649 bytes
コンパイル時間 261 ms
コンパイル使用メモリ 81,664 KB
実行使用メモリ 102,884 KB
最終ジャッジ日時 2024-10-07 02:14:04
合計ジャッジ時間 5,472 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 41
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.readline
N = int(input())
e = [[] for _ in range(N + 1)]
for _ in range(N - 1):
  u, v = map(int, input().split())
  e[u].append(v)
  e[v].append(u)

s = [1]
vis = [0] * (N + 1)
parent = [0] * (N + 1)
vis[1] = 1
order = []
while len(s):
  x = s.pop()
  order.append(x)
  for y in e[x]:
    if vis[y]: continue
    parent[y] = x
    vis[y] = 1
    s.append(y)

size = [1] * (N + 1)
for y in order[: : -1]:
  x = parent[y]
  size[x] += size[y]

res = N ** 2
for x in range(1, N + 1):
  for y in e[x]:
    if y == parent[x]:
      res += (N - size[x]) * size[x]
      continue
    res += size[y] * (N - size[y])

print(res)
0