Problem:


Score : 400 points

Problem Statement

Given is a rooted tree with N vertices numbered 1 to N.
The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.

Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.

Now, the following Q operations will be performed:

Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.

Find the value of the counter on each vertex after all operations.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq Q \leq 2 \times 10^5

1 \leq a_i < b_i \leq N

1 \leq p_j \leq N

1 \leq x_j \leq 10^4

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q

Output

Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between.

Sample Input 1

4 3
1 2
2 3
2 4
2 10
1 100
3 1

Sample Output 1

100 110 111 110

The tree in this input is as follows:

Each operation changes the values of the counters on the vertices as follows:

Operation 1: Increment by 10 the counter on every vertex contained in the subtree rooted at Vertex 2, that is, Vertex 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 0, 10, 10, 10, respectively.

Operation 2: Increment by 100 the counter on every vertex contained in the subtree rooted at Vertex 1, that is, Vertex 1, 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 110, 110, respectively.

Operation 3: Increment by 1 the counter on every vertex contained in the subtree rooted at Vertex 3, that is, Vertex 3. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 111, 110, respectively.

Sample Input 2

6 2
1 2
1 3
2 4
3 6
2 5
1 10
1 10

Sample Output 2

20 20 20 20 20 20



Sample input:
4 3
1 2
2 3
2 4
2 10
1 100
3 1


Sample output:
100 110 111 110

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline
from collections import defaultdict
from heapq import heappop, heappush

from decimal import *

##### リストの 二分木検索 #####
# bisect_left(lists, 3)
# bisect_right(lists, 3)

##### プライオリティキュー #####
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除＆その最小値を出力

# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと

##### タプルリストのソート #####
# sorted(ans) #(a, b) -> 1st : aの昇順, 2nd : bの昇順
# sorted(SP, key=lambda x:(x[0],-x[1])) #(a, b) -> 1st : aの昇順, 2nd : bの降順
# sorted(SP, key=lambda x:(-x[0],x[1])) #(a, b) -> 1st : aの降順, 2nd : bの昇順
# sorted(SP, key=lambda x:(-x[0],-x[1])) #(a, b) -> 1st : aの降順, 2nd : bの降順

# sorted(SP, key=lambda x:(x[1])) #(a, b) -> 1st : bの昇順
# sorted(SP, key=lambda x:(-x[1])) #(a, b) -> 1st : bの降順

##### 累乗 #####
# pow(x, y, z) -> x**y % z

##### 割り算の切り上げ #####
# tmp = -(-4 // 3)

##### dict の for文 #####
# for k, v in d.items():
#     print(k, v)

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))
def inputStr(): return input()[:-1]

inf = float('inf')
mod = 1000000007

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

def main():
	N,Q = inputMap()
	AB = [list(map(int,input().split())) for _ in range(N-1)]
	PX = [list(map(int,input().split())) for _ in range(Q)]

	graph = [[] for _ in range(N+1)]

	for a,b in AB:
		graph[a].append(b)
		graph[b].append(a)

	#print(graph)

	counter = [0 for _ in range(N+1)]
	parent = [None for _ in range(N+1)]

	for p,x in PX:
		counter[p] += x

	dfs(graph,parent,counter,1)

	ans = " ".join(map(str,counter[1:]))
	print(ans)

def dfs(graph,parent,counter,edge):
    stk = []
    stk.append(edge)
    while len(stk) > 0:
        p = stk.pop()
        for e in graph[p]:
            if parent[p] == e:
                continue
            else:
                parent[e] = p
                counter[e] += counter[p]
                stk.append(e)

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# nCr mod m
# rがn/2に近いと非常に重くなる
def combination(n, r, mod=10**9+7):
    r = min(r, n-r)
    res = 1
    for i in range(r):
        res = res * (n - i) * modinv(i+1, mod) % mod
    return res

# mを法とするaの乗法的逆元
def modinv(a, mod=10**9+7):
    return pow(a, mod-2, mod)

def egcd(a, b):
    if a == 0:
        return b, 0, 1
    else:
        g, y, x = egcd(b % a, a)
        return g, x - (b // a) * y, y

# nHr mod m
# 問題によって、combination()を切り替えること
def H(n, r, mod=10**9+7):
	# comb = Combination(n+r-1, mod)
	# return comb(n+r-1, r)
    return combination(n+r-1, r, mod)


class Combination:
    """
    O(n)の前計算を1回行うことで，O(1)でnCr mod mを求められる
    n_max = 10**6のとき前処理は約950ms (PyPyなら約340ms, 10**7で約1800ms)
    使用例：
    comb = Combination(1000000)
    print(comb(5, 3))  # 10
    """
    def __init__(self, n_max, mod=10**9+7):
        self.mod = mod
        self.modinv = self.make_modinv_list(n_max)
        self.fac, self.facinv = self.make_factorial_list(n_max)

    def __call__(self, n, r):
        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod

    def make_factorial_list(self, n):
        # 階乗のリストと階乗のmod逆元のリストを返す O(n)
        # self.make_modinv_list()が先に実行されている必要がある
        fac = [1]
        facinv = [1]
        for i in range(1, n+1):
            fac.append(fac[i-1] * i % self.mod)
            facinv.append(facinv[i-1] * self.modinv[i] % self.mod)
        return fac, facinv

    def make_modinv_list(self, n):
        # 0からnまでのmod逆元のリストを返す O(n)
        modinv = [0] * (n+1)
        modinv[1] = 1
        for i in range(2, n+1):
            modinv[i] = self.mod - self.mod//i * modinv[self.mod%i] % self.mod
        return modinv

if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
import sys
from queue import deque
input = sys.stdin.readline

def main():
    N, Q = list(map(int, input().split()))
    graph = [[] for i in range(N)]
    # 最初にroot pointを定めて:
    # graph構造に大して点を与える...
    for i in range(N-1):
        a, b = list(map(int, input().split()))
        graph[a-1].append(b-1)
        graph[b-1].append(a-1)
    
    points = [0] * N
    for _ in range(Q):
        p, x = list(map(int, input().split()))
        points[p-1] += x
    
    visited = [False] * N
    
    nodes = deque([0])

    while nodes:
        node = nodes.pop()
        visited[node] = True
        for _node in graph[node]:
            if visited[_node]:
                continue
            points[_node] += points[node]
            nodes.append(_node)
    
    print(*points)
    
main()

Submission status: Accepted

Solution code:
from collections import deque

n, q = map(int, input().split())

g = [[] for _ in range(n)]
for _ in range(n-1):
    a, b = map(int, input().split())
    g[a-1].append(b-1)
    g[b-1].append(a-1)

c = [0] * n
for _ in range(q):
    p, x = map(int, input().split())
    c[p-1] += x

q = deque([0])
flag = [False] * n
while q:
    v = q.pop()
    flag[v] = True
    for e in g[v]:
        if flag[e]:
            continue
        c[e] += c[v]
        q.append(e)

print(*c)

Submission status: Accepted

Solution code:
N, Q = map(int, input().split())
edge = [[] for _ in range(N)]
for i in range(N-1):
    a,b = map(int, input().split())
    edge[a-1].append(b-1)
    edge[b-1].append(a-1)

ans = [0]*N
for i in range(Q):
    p, x = map(int, input().split())
    ans[p-1] += x

from collections import deque

visited = [False]*N
d = deque([0])
while len(d)>0:
    v = d.popleft()
    visited[v]= True
    for u in edge[v]:
        if visited[u]==False:
            ans[u] += ans[v]
            visited[u]=True
            d.append(u)

print(*ans, sep=' ')

Submission status: Accepted

Solution code:
from collections import deque

N, Q = map(int, input().split())

G=[[] for i in range(N)]
A =[0]*N

for i in range(N-1):
    a, b = map(int, input().split())
    G[a-1].append(b-1)
    G[b-1].append(a-1)

for i in range(Q):
    p, x = map(int, input().split())
    A[p-1] += x

queue = deque([0])
visited= [0]*N
while queue:
    a = queue.popleft()
    visited[0] = 1
    for i in G[a]:
        if visited[i] == 0:
            A[i] += A[a]
            visited[a] = 1
            queue.append(i)

print(*A)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline
def main():
    n,q=map(int,input().split())
    graph=[[] for _ in range(n+1)]
    ab=[list(map(int,input().split())) for _ in range(n-1)]
    for a,b in ab:
        graph[a].append(b)
        graph[b].append(a)
    px=[list(map(int,input().split())) for _ in range(q)]
    seen=[0]*(n+1)
    ans=[0]*(n+1)
    for p,x in px:
        ans[p]+=x
    def dfs(i):
        seen[i]=1
        for li in graph[i]:
            if seen[li]==0:
                ans[li]+=ans[i]
                dfs(li)
    dfs(1)
    print(' '.join(map(str,ans[1:])))
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**8)

input=sys.stdin.readline

n,q=map(int,input().split())

tree=[[] for _ in range(n)]

for _ in range(n-1):
    a,b=map(int,input().split())
    tree[a-1].append(b-1)
    tree[b-1].append(a-1)

point=[0]*n
for _ in range(q):
    q,x=map(int,input().split())
    point[q-1]+=x

result=["no"]*n

def counter(chouten,count):
    global result,point,tree
    count+=point[chouten]
    result[chouten]=count

    #print(chouten,result)

    for item in tree[chouten]:
        if result[item]=="no":
            counter(item,count)

counter(0,0)

result=map(str,result)
print(" ".join(result))

Submission status: Accepted

Solution code:
from collections import defaultdict
import sys
sys.setrecursionlimit(10**9)
input=sys.stdin.readline

def dfs(u,s):
  visited[u]=True
  ans_list[u]=s+dic_score[u]
  
  for v in tree_list[u]:
    if not visited[v]:
      dfs(v,ans_list[u])    
  return s

N,Q=map(int,input().split())

tree_list=[[] for _ in range(N+1)]
for i in range(N-1):
  a,b=map(int,input().split())
  tree_list[a].append(b)
  tree_list[b].append(a)
#print(tree_list)

dic_score=defaultdict(int)
for i in range(Q):
  p,x=map(int,input().split())
  dic_score[p]+=x

ans_list=[0]*(N+1)
visited=[False]*(N+1)
dfs(1,0)

print(*ans_list[1:])

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)
input=sys.stdin.readline

def dfs(u,par):
  ans_list[u]+=ans_list[par]  
  for v in tree_list[u]:
    if v!=par:
      dfs(v,u)      
  return

N,Q=map(int,input().split())

tree_list=[[] for _ in range(N+1)]
for i in range(N-1):
  a,b=map(int,input().split())
  tree_list[a].append(b)
  tree_list[b].append(a)
#print(tree_list)

ans_list=[0]*(N+1)
for i in range(Q):
  p,x=map(int,input().split())
  ans_list[p]+=x

dfs(1,0)

print(*ans_list[1:])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
n, q = map(int, input().split())
node = [0] * n
to = [[] for _ in range(n)]
for _ in range(n-1):
    a, b = map(int, input().split())
    to[b-1].append(a-1)
    to[a-1].append(b-1)
for _ in range(q):
    p, x = map(int, input().split())
    node[p-1]+=x

def dfs(i, source, count=0):
    node[i]+=count
    for next_node in to[i]:
        if next_node == source: continue 
        dfs(next_node, i, node[i])
dfs(0, -1, 0)

print(' '.join(list(map(str, node))))

Submission status: Accepted

Solution code:
from collections import deque

N, Q = map(int, input().split())

G=[[] for i in range(N)]
A =[0]*N

for i in range(N-1):
    a, b = map(int, input().split())
    G[a-1].append(b-1)
    G[b-1].append(a-1)

for i in range(Q):
    p, x = map(int, input().split())
    A[p-1] += x

queue = deque([0])
visited= [0]*N
while queue:
    a = queue.popleft()
    visited[0] = 1
    for i in G[a]:
        if visited[i] == 0:
            A[i] += A[a]
            visited[a] = 1
            queue.append(i)

print(*A)

Submission status: Accepted

Solution code:
N, Q = map(int, input().split())

edge = [[] for _ in range(N)]
counter = [0 for _ in range(N + 1)]

for _ in range(N - 1):
    a, b = map(int, input().split())
    edge[a - 1].append(b - 1)
    edge[b - 1].append(a - 1)

for _ in range(Q):
    p, x = map(int, input().split())
    counter[p - 1] += x

stack = [(0, -1)]
while stack:
    s, parent = stack.pop()
    counter[s] += counter[parent]
    for n in edge[s]:
        if n == parent:
            continue
        stack.append((n, s))

ans = " ".join(map(str, counter[:N]))
print(ans)

Submission status: Accepted

Solution code:
N, Q = map(int, input().split())

edge = [[] for _ in range(N)]
counter = [0 for _ in range(N + 1)]

for _ in range(N - 1):
    a, b = map(int, input().split())
    edge[a - 1].append(b - 1)
    edge[b - 1].append(a - 1)

for _ in range(Q):
    p, x = map(int, input().split())
    counter[p - 1] += x

stack = [(0, -1)]
while stack:
    s, parent = stack.pop()
    counter[s] += counter[parent]
    for n in edge[s]:
        if n == parent:
            continue
        stack.append((n, s))

[print(c, end=" ") for c in counter[:N]]

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
edges=[[] for _ in range(n)]
for _ in range(n-1):
  a,b=map(int,input().split())
  a-=1
  b-=1
  edges[a].append(b)
  edges[b].append(a)
list=[0]*n
for _ in range(m):
  p,q=map(int,input().split())
  list[p-1]+=q
stack=[0]
lity=[0]*n
while stack:
  x=stack.pop()
  lity[x]=1
  for y in edges[x]:
    if lity[y]==1:
      continue
    list[y]+=list[x]
    stack.append(y)
print(*list)

Submission status: Accepted

Solution code:
def dfs(graph,parent,counter,edge):
    stk = []
    stk.append(edge)
    while len(stk) > 0:
        p = stk.pop()
        for e in graph[p]:
            if parent[p] == e:
                continue
            else:
                parent[e] = p
                counter[e] += counter[p]
                stk.append(e)

def main():
    #全体に同じものを足すときは累積和を考えたい
    N,Q = map(int,input().split())
    AB = [list(map(int,input().split())) for _ in range(N-1)]
    PX = [list(map(int,input().split())) for _ in range(Q)]

    graph = [[] for _ in range(N+1)]

    for a,b in AB:
        graph[a].append(b)
        graph[b].append(a)
    #どちらが親か分からないがとりあえずつながっている
    #どちらが親かは後で判断

    counter = [0 for _ in range(N+1)]
    #counter[i]:i番目の頂点のカウンター
    parent = [None for _ in range(N+1)]

    for p,x in PX:
        counter[p] += x

    dfs(graph,parent,counter,1)

    ans = " ".join(map(str,counter[1:]))
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque

n, q = map(int, input().split())
dist = [[] for i in range(n)]
for i in range(n - 1):
    a, b = map(int, input().split())
    dist[a - 1].append(b - 1)
    # aftercontest対策
    dist[b - 1].append(a - 1)
value = [0 for i in range(n)]

# 1つ目の[1, 10]と2つ目の[1, 10]混ぜても問題なし
for i in range(q):
    p, x = map(int, input().split())
    value[p - 1] += x
#  重複を防ぐ
ignore = [0] * n
ignore[0] = 1

pos = deque([0])
# 上から順に自身のvalueの値を子のvalueに加算していく
# value [100, 10, 1, 0]
# pos.popleft() = 1 → [100, 10 + 100, 1 + 100, 0 + 100]
# pos.popleft() = 2 → [100, 110, 101 + 10, 100 + 10]
while len(pos) > 0:
    u = pos.popleft()
    for i in dist[u]:
        if ignore[i] == 0:
            ignore[i] = 1
            value[i] += value[u]
            pos.append(i)
# 覚える
print(*value)

Submission status: Accepted

Solution code:
from collections import deque

N, Q = map(int, input().split())
X = [list(map(int, input().split())) for _ in range(N - 1)]
Y = [list(map(int, input().split())) for _ in range(Q)]

graph = [[] for _ in range(N + 1)]
for a, b in X:
    graph[a].append(b)
    graph[b].append(a)

ctr = [0] * (N + 1)
for p, x in Y:
    ctr[p] += x

# BFS
visited = [False] * (N + 1)
visited[1] = True
q = deque([1])
while q:
    u = q.popleft()
    for v in graph[u]:
        if visited[v]:
            continue
            
        ctr[v] += ctr[u]
        visited[v] = True
        q.append(v)
        
print(*ctr[1:])

Submission status: Accepted

Solution code:
from __future__ import print_function

from functools import reduce
from operator import mul
from collections import Counter
from collections import deque
from itertools import accumulate
from queue import Queue
from queue import PriorityQueue as pq
from heapq import heapreplace
from heapq import heapify
from heapq import heappushpop
from heapq import heappop
from heapq import heappush
import heapq
import time
import random
import bisect
import itertools
import collections
from fractions import Fraction
import fractions
import string
import math
import operator
import functools
import copy
import array
import re
import sys
sys.setrecursionlimit(500000)


input = sys.stdin.readline


def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)
    return

# from fractions import gcd
# from math import gcd

# def lcm(n, m):
#     return int(n * m / gcd(n, m))


# def coprimize(p, q):
#     common = gcd(p, q)
#     return (p // common, q // common)


# def find_gcd(list_l):
#     x = reduce(gcd, list_l)
#     return x


def combinations_count(n, r):
    r = min(r, n - r)
    numer = reduce(mul, range(n, n - r, -1), 1)
    denom = reduce(mul, range(1, r + 1), 1)
    return numer // denom


def main():
    #
    n, q = map(int, input().strip().split())
    G = [[] for _ in range(n)]
    for i in range(0, n-1):
        temp1, temp2 = map(lambda x: int(x) - 1, input().strip().split())
        G[temp1].append(temp2)
        G[temp2].append(temp1)

    px = [0 for _ in range(n)]
    for _ in range(q):
        temp1, temp2 = map(int, input().strip().split())
        px[temp1-1] += temp2

    #
    # eprint('px ', end=':\n')
    # eprint(px)

    # 木の頂点から順番に頂点を見ていき，頂点j
    # 頂点iについて，その子すべてにカウンタを"配る"
    usedlist = [False for _ in range(n)]
    imos = [0 for _ in range(n)]
    Q = Queue()

    # 木の頂点から順番に頂点を見ていき，頂点j
    Q.put(0)
    while not(Q.empty()):
        v = Q.get()
        usedlist[v] = True
        imos[v] += px[v]
        for u in G[v]:  # uは，「今見ているノード」の「子ノード」を表す
            if usedlist[u] == False:
                imos[u] += imos[v]
                Q.put(u)
    # eprint('imos ', end=':\n')
    # eprint(imos)

    #
    for value in imos:
        print(value, end=" ")


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N, Q = map(int, input().split())
to = [[] for _ in range(N)]
for _ in range(N-1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    to[a].append(b)
    to[b].append(a)

count = [0] * N
for _ in range(Q):
    p, x = map(int, input().split())
    p -= 1
    count[p] += x

stack = [0]
visited = [0] * N
while stack:
    v = stack.pop()
    visited[v] = 1
    for next_v in to[v]:
        if visited[next_v] == 1:
            continue
        count[next_v] += count[v]
        stack.append(next_v)
print(*count)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 8)
input = sys.stdin.readline

def main():
    #入力
    N, Q = (int(_) for _ in input().split())
    edge = [[int(_) for _ in input().split()] for __ in range(N-1)]
    query = [[int(_) for _ in input().split()] for __ in range(Q)]

    tree = [[] for _ in range(N+1)]
    for a, b in edge:
        tree[a].append(b)
        tree[b].append(a)

    cc = [0] * (N+1)
    seen = [False] * (N+1)

    for p, x in query:
        cc[p] += x

    def dfs(x):
        for p in tree[x]:
            if seen[p] == False:
                seen[p] = True
                cc[p] += cc[x]
                dfs(p)
        return

    seen[1] = True
    dfs(1)

    print(*cc[1:])

    return

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

n, q = map(int, input().split())
edges = [[] for _ in range(n)]
for _ in range(n-1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    edges[a].append(b)
    edges[b].append(a)

count = [0]*n
for _ in range(q):
    p, x = map(int, input().split())
    count[p-1] += x

stack = [0]
visited = [0]*n
while stack:
    v = stack.pop()
    visited[v] = 1
    for v2 in edges[v]:
        if visited[v2] == 1:
            continue
        count[v2] += count[v]
        stack.append(v2)

print(*count)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)

n, q = map(int, input().split())
edges = [[] for _ in range(n)]

for _ in range(n-1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    edges[a].append(b)
    edges[b].append(a)

count = [0]*n
for i in range(q):
    p, x = map(int, input().split())
    count[p-1] += x


def dfs(v, parent):
    for v2 in edges[v]:
        if v2 == parent:
            continue
        count[v2] += count[v]
        dfs(v2, v)


dfs(0, None)
print(*count)

Submission status: Accepted

Solution code:
#ABC138D
#node:節 edge:枝
def main():
    import sys
    sys.setrecursionlimit(200005)
    N, Q = map(int, sys.stdin.readline().split())
    edge = [tuple(map(int, sys.stdin.readline().split())) for _ in range(N-1)]
    #1:ノードのリストを作る
    nodeL = [[] for _ in range(N)]
    for a, b in edge:
        nodeL[a-1].append(b-1)
        nodeL[b-1].append(a-1)
    #print(nodeL)
    px = [tuple(map(int, sys.stdin.readline().split())) for _ in range(Q)]
    #print(px)
    score = [0 for i in range(N)]
    for p, x in px:
        score[p-1] +=x
    #print(score)
    result = score.copy()
    
    def dfs(p, g=-1):
        for c in nodeL[p]:
            if c !=g:
                score[c] +=score[p]
                dfs(c, p)
    
    
    dfs(0)
    print(*score)
    


if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
# D - Ki

from collections import deque

n, q = map(int, input().split())

graph = [[] for _ in range(n)]
for _ in range(n-1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

cnt = [0]*n
for _ in range(q):
    p, x = map(int, input().split())
    p -= 1
    cnt[p] += x

done = [-1]*n
done[0] = 1
d = deque()
d.append((0, 0))

while len(d)>0:
    v = d.popleft()
    cnt[v[0]] += v[1]
    done[v[0]] = 1
    for i in graph[v[0]]:
        if done[i]<0:
            d.append((i, cnt[v[0]]))

print(' '.join(map(str, cnt)))

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
from collections import deque
#グラフの連結成分を調べる
def Graph(ab):
    G=[[] for i in range(n)]
    for a,b in ab:
        G[a-1].append(b)
        G[b-1].append(a)
    return G

n, q = map(int,input().split())
ab = [list(map(int,input().split())) for i in range(n - 1)]
px = [list(map(int,input().split())) for i in range(q)]

G = Graph(ab)
ki = [0] * n

for i in range(q):
    root, score = px[i]
    ki[root - 1] += score

q = deque()
q.append((1, -1))

while q:
    v, p = q.popleft()
    for next in G[v - 1]:
        if next == p:continue
        ki[next - 1] += ki[v - 1]
        q.append((next, v))
print(*ki)

Submission status: Accepted

Solution code:
from collections import deque
#グラフの連結成分を調べる
def Graph(ab):
    G=[[] for i in range(n)]
    for a,b in ab:
        G[a-1].append(b)
        G[b-1].append(a)
    return G

n, q = map(int,input().split())
ab = [list(map(int,input().split())) for i in range(n - 1)]
px = [list(map(int,input().split())) for i in range(q)]

G = Graph(ab)
ki = [0] * n

for i in range(q):
    root, score = px[i]
    ki[root - 1] += score

q = deque()
q.append((1, -1))

while q:
    v, p = q.popleft()
    for next in G[v - 1]:
        if next == p:continue
        ki[next - 1] += ki[v - 1]
        q.append((next, v))
print(*ki)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**9)
from collections import deque, defaultdict
n, q = map(int, input().split())
#隣接リスト
G = defaultdict(lambda:[])
#################################
for _ in range(n-1):
    a, b = map(int, input().split())
    a, b = a-1, b-1
    G[a].append(b)
    G[b].append(a)
    
#################################

#深さ優先探索でトポロジカル順序を決める
#右奥から調べていく
parent = [0]*n #p[i]:頂点iの親
order = [] #トポロジカル順序
def dfs():
    parent[0] = -1
    stack = []
    u = 0
    stack.append(u)
    while stack:
        x = stack.pop()
        order.append(x)
        for v in G[x]:
            if v == parent[x]:
                continue
            parent[v] = x
            stack.append(v)

dfs()
################################
point = [0]*n
for i in range(q):
    p, x = map(int, input().split())
    p -=1
    point[p] += x

for i in order:
    if parent[i] != -1:
        point[i] += point[parent[i]]

print(*point)

Submission status: Accepted

Solution code:
import collections

n,q=map(int,input().split())
cnt=[0]*(n+1)
g=[[] for i in range(n+1)]
for i in range(n-1):
  a,b=map(int,input().split())
  g[a].append(b)
  g[b].append(a)
for i in range(q):
  v,val=map(int,input().split())
  cnt[v]+=val
q=collections.deque()
q.append(1)
checked=[0]*(n+1)
while q:
  v=q.pop()
  checked[v]=1
  for i in g[v]:
    if checked[i]==1:
      continue
    cnt[i]+=cnt[v]
    q.append(i)
print(*cnt[1:])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000000)
n, q = map(int, input().split())
edges = [[] for _ in range(n)]
for i in range(n-1):
    a, b = map(int, input().split())
    edges[a-1].append(b-1)
    edges[b-1].append(a-1)

counter = [0]*n
for i in range(q):
    p, x = map(int, input().split())
    counter[p-1] += x
visited = [0]*n


def dfs(parent):
    visited[parent] = 1
    for c in edges[parent]:
        if visited[c] == 1:
            continue
        else:
            counter[c] += counter[parent]
            dfs(c)


dfs(0)
print(*counter)