結果

問題 No.1418 Sum of Sum of Subtree Size
ユーザー marroncastlemarroncastle
提出日時 2021-03-15 17:26:31
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 268 ms / 2,000 ms
コード長 1,232 bytes
コンパイル時間 227 ms
コンパイル使用メモリ 82,048 KB
実行使用メモリ 97,196 KB
最終ジャッジ日時 2024-04-24 19:55:33
合計ジャッジ時間 8,077 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 50 ms
53,760 KB
testcase_01 AC 45 ms
53,760 KB
testcase_02 AC 45 ms
53,760 KB
testcase_03 AC 268 ms
96,512 KB
testcase_04 AC 252 ms
96,512 KB
testcase_05 AC 246 ms
96,896 KB
testcase_06 AC 243 ms
96,384 KB
testcase_07 AC 257 ms
96,384 KB
testcase_08 AC 188 ms
89,472 KB
testcase_09 AC 127 ms
81,664 KB
testcase_10 AC 128 ms
81,920 KB
testcase_11 AC 109 ms
79,488 KB
testcase_12 AC 171 ms
87,168 KB
testcase_13 AC 187 ms
88,448 KB
testcase_14 AC 197 ms
89,088 KB
testcase_15 AC 170 ms
84,608 KB
testcase_16 AC 98 ms
77,312 KB
testcase_17 AC 97 ms
77,696 KB
testcase_18 AC 234 ms
93,184 KB
testcase_19 AC 108 ms
79,488 KB
testcase_20 AC 83 ms
71,552 KB
testcase_21 AC 158 ms
84,864 KB
testcase_22 AC 150 ms
84,224 KB
testcase_23 AC 85 ms
73,600 KB
testcase_24 AC 83 ms
73,088 KB
testcase_25 AC 83 ms
72,320 KB
testcase_26 AC 85 ms
73,088 KB
testcase_27 AC 56 ms
61,312 KB
testcase_28 AC 70 ms
67,584 KB
testcase_29 AC 88 ms
74,496 KB
testcase_30 AC 85 ms
73,984 KB
testcase_31 AC 78 ms
70,656 KB
testcase_32 AC 84 ms
72,320 KB
testcase_33 AC 103 ms
80,384 KB
testcase_34 AC 221 ms
95,872 KB
testcase_35 AC 124 ms
83,840 KB
testcase_36 AC 89 ms
78,464 KB
testcase_37 AC 182 ms
97,196 KB
testcase_38 AC 171 ms
95,412 KB
testcase_39 AC 46 ms
53,888 KB
testcase_40 AC 47 ms
54,016 KB
testcase_41 AC 45 ms
53,760 KB
testcase_42 AC 47 ms
54,272 KB
testcase_43 AC 46 ms
53,888 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.readline
from collections import deque
class Tree:
  def __init__(self, N):
    self.V = N
    self.edge = [[] for _ in range(N)]
    self.order = []
  
  def add_edges(self, ind=1, bi=True):
    for i in range(self.V-1):
      a,b = map(int, input().split())
      a -= ind; b -= ind
      self.edge[a].append(b)
      if bi: self.edge[b].append(a)

  def add_edge(self, a, b, bi=True):
    self.edge[a].append(b)
    if bi: self.edge[b].append(a)

  def dp(self, start):
    global ans
    stack = deque([start])
    self.parent = [self.V]*self.V; self.parent[start] = -1
    self.order.append(start)
    #記録したい値の配列を定義
    self.dp = [1]*self.V
    while stack:
      v = stack.pop()
      for u in self.edge[v]:
        if u==self.parent[v]: continue
        self.parent[u]=v
        stack.append(u); self.order.append(u)
    for v in self.order[::-1]:
      cum = 0
      for u in self.edge[v]:
        if u==self.parent[v]: continue
        ans += (self.dp[u]+1) * (N-self.dp[u])
        cum += self.dp[u]
        self.dp[v] += self.dp[u] #帰りがけ処理
      ans += (cum+1) * (N-cum)

N = int(input())
G = Tree(N)
G.add_edges(ind=1, bi=True)
ans = 0
G.dp(0)
print(ans)
0