結果
| 問題 | No.1418 Sum of Sum of Subtree Size | 
| コンテスト | |
| ユーザー |  | 
| 提出日時 | 2021-03-15 17:26:31 | 
| 言語 | PyPy3 (7.3.15) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 265 ms / 2,000 ms | 
| コード長 | 1,232 bytes | 
| コンパイル時間 | 175 ms | 
| コンパイル使用メモリ | 82,048 KB | 
| 実行使用メモリ | 96,880 KB | 
| 最終ジャッジ日時 | 2024-11-07 04:47:17 | 
| 合計ジャッジ時間 | 7,900 ms | 
| ジャッジサーバーID (参考情報) | judge3 / judge4 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 3 | 
| other | AC * 41 | 
ソースコード
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)
            
            
            
        