結果
| 問題 | 
                            No.1637 Easy Tree Query
                             | 
                    
| コンテスト | |
| ユーザー | 
                             lam6er
                         | 
                    
| 提出日時 | 2025-03-20 20:56:54 | 
| 言語 | PyPy3  (7.3.15)  | 
                    
| 結果 | 
                             
                                AC
                                 
                             
                            
                         | 
                    
| 実行時間 | 349 ms / 2,000 ms | 
| コード長 | 1,509 bytes | 
| コンパイル時間 | 302 ms | 
| コンパイル使用メモリ | 82,656 KB | 
| 実行使用メモリ | 101,456 KB | 
| 最終ジャッジ日時 | 2025-03-20 20:57:09 | 
| 合計ジャッジ時間 | 10,292 ms | 
| 
                            ジャッジサーバーID (参考情報)  | 
                        judge2 / judge3 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 2 | 
| other | AC * 33 | 
ソースコード
import sys
from collections import deque
def main():
    n, q = map(int, sys.stdin.readline().split())
    adj = [[] for _ in range(n+1)]
    for _ in range(n-1):
        a, b = map(int, sys.stdin.readline().split())
        adj[a].append(b)
        adj[b].append(a)
    
    # BFS to build parent and children structure
    parent = [0] * (n+1)
    children = [[] for _ in range(n+1)]
    visited = [False] * (n+1)
    queue = deque([1])
    visited[1] = True
    parent[1] = -1  # mark root's parent
    
    while queue:
        u = queue.popleft()
        for v in adj[u]:
            if not visited[v]:
                visited[v] = True
                parent[v] = u
                children[u].append(v)
                queue.append(v)
    
    # Calculate subtree sizes using iterative post-order traversal
    subtree_size = [1] * (n+1)
    stack = [(1, False)]
    
    while stack:
        node, visited_flag = stack.pop()
        if not visited_flag:
            stack.append((node, True))
            # Add children in reverse to process them in order
            for child in reversed(children[node]):
                stack.append((child, False))
        else:
            for child in children[node]:
                subtree_size[node] += subtree_size[child]
    
    # Process each query and print the sum
    total = 0
    for _ in range(q):
        p, x = map(int, sys.stdin.readline().split())
        total += subtree_size[p] * x
        print(total)
if __name__ == "__main__":
    main()
            
            
            
        
            
lam6er