結果

問題 No.1637 Easy Tree Query
ユーザー tobusakana
提出日時 2022-11-27 14:10:00
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 280 ms / 2,000 ms
コード長 1,237 bytes
コンパイル時間 323 ms
コンパイル使用メモリ 81,940 KB
実行使用メモリ 92,252 KB
最終ジャッジ日時 2024-10-04 02:12:12
合計ジャッジ時間 9,986 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
readline = sys.stdin.readline

N,Q = map(int,readline().split())
G = [[] for i in range(N)]
indegree = [0] * N
for _ in range(N - 1):
    a,b = map(int,readline().split())
    G[a - 1].append(b - 1)
    G[b - 1].append(a - 1)
    indegree[a - 1] += 1
    indegree[b - 1] += 1
    
# 入り次数が1の頂点からスタートして、自分は部分木サイズ1
# それを次の親に対していく
cnt = [1] * N
starts = []
for i in range(1, N):
    if indegree[i] == 1:
        starts.append(i)
        
dist_from_start = [0] * N
stack = [[0, 0, -1]]
while stack:
    v,d,p = stack.pop()
    dist_from_start[v] = d
    for child in G[v]:
        if child == p:
            continue
        stack.append([child, d + 1, v])

while starts:
    next_starts = []
    for s in starts:
        indegree[s] -= 1
        for child in G[s]:
            if dist_from_start[child] > dist_from_start[s]:
                continue
            cnt[child] += cnt[s]
            indegree[child] -= 1
            if indegree[child] == 1 and child != 0:
                next_starts.append(child)
    starts = next_starts
    
ans = 0        
for _ in range(Q):
    p,x = map(int,readline().split())
    ans += cnt[p - 1] * x
    print(ans)
0