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:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())


n, q = li()
edge = [list(li_()) for _ in range(n-1)]
query = [list(li()) for _ in range(q)]

# 各頂点に指定の数字を入れる
num = [0]*n
for pi, xi in query:
    pi -= 1
    num[pi] += xi

# 木を構築
tree = [[] for _ in range(n)]
for ai, bi in edge:
    tree[ai].append(bi)
    tree[bi].append(ai)


# ルートから、親+自分の数字を入れる
visited = [False]*n
stack = [0]
visited[0] = True

while stack:
    cur = stack.pop()
    for nex in tree[cur]:
        if visited[nex]:
            continue

        visited[nex] = True
        num[nex] += num[cur]
        stack.append(nex)

# 出力
print(*num)

Submission status: Accepted

Solution code:
from collections import deque
N, Q = map(int, input().split())
G = [[] for _ in range(N)]
count = [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())
    count[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
        count[e]+=count[v]
        q.append(e)
print(' '.join(list(map(str, count))))

Submission status: Accepted

Solution code:
from collections import deque


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

tree = [[] for i in range(n)]
for i in range(n-1):
    tree[info[i][0] - 1].append(info[i][1] - 1)
    tree[info[i][1] - 1].append(info[i][0] - 1)

memo = {}
for i in range(n):
    memo[i] = 0
for i in range(q):
    memo[p[i][0] - 1] += p[i][1]

dp = [0] * n
visited = [False]*n
q = deque([0])
visited[0] = True
dp[0] = memo[0]

while q:
    pos = q.popleft()
    for next_pos in tree[pos]:
        if visited[next_pos]:
            continue
        visited[next_pos] = True
        dp[next_pos] += dp[pos] + memo[next_pos]
        q.append(next_pos)
print(*dp)

Submission status: Accepted

Solution code:
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())

N,Q = inpl()

lines = defaultdict(set)
for _ in range(N-1):
    a,b = inpl()
    a,b = a-1,b-1
    lines[a].add(b)
    lines[b].add(a)

adds = [0]*N
for _ in range(Q):
    p,x = inpl()
    adds[p-1] += x

visited = [False]*N
ans = [0]*N

q = queue.LifoQueue()
q.put([0,0])

while not q.empty():
    x,cnt = q.get()
    visited[x] = True
    cnt += adds[x]
    ans[x] += cnt
    for t in lines[x]:
        if not visited[t]:
            q.put([t,cnt])

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

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**9)
 
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()


n,q = na()
g = [[] for i in range(n)]
c = [0]*n

for i in range(n-1):
    a,b = na()
    g[a-1].append(b-1)
    g[b-1].append(a-1)
for i in range(q):
    p,x = na()
    c[p-1] += x

def f(b,a,r):
    r += c[a]
    c[a] = r
    for i in g[a]:
        if i != b:
            f(a,i,r)

f(-1,0,0)
print(' '.join([str(s) for s in c]))

Submission status: Accepted

Solution code:
from collections import deque
import sys
readline = sys.stdin.readline
N, Q = map(int, readline().split())
G = [[] for i in range(N)]
C = [0] * N
for i in range(N-1):
    a, b = map(int, readline().split())
    G[a-1].append(b-1)
    G[b-1].append(a-1)
for i in range(Q):
    p, x = map(int, readline().split())
    C[p-1] += x
used = [0]*N
used[0] = 1
que = deque([0])
while que:
    v = que.popleft()
    c = C[v]
    for w in G[v]:
        if used[w]:
            continue
        used[w] = 1
        C[w] += c
        que.append(w)
print(*C)

Submission status: Accepted

Solution code:
n, q = map(int, input().split())
g = [[] for _ in range(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)
li = [0] * n
for i in range(q):
  p, x = map(int, input().split())
  li[p - 1] += x
s = [0]
done = [0] * n
done[0] = 1
while s:
  d = s.pop()
  for node in g[d]:
    if done[node] == 0:
      li[node] += li[d]
      s.append(node)
      done[node] = 1
print(' '.join(map(str, li)))

Submission status: Accepted

Solution code:
import sys
        
def getpar(Edge, p):
    N = len(Edge)
    par = [0]*N
    par[0] = -1
    par[p]  -1
    stack = [p]
    visited = set([p])
    while stack:
        vn = stack.pop()
        for vf in Edge[vn]:
            if vf in visited:
                continue
            visited.add(vf)
            par[vf] = vn
            stack.append(vf)
    return par

def topological_sort_tree(E, r):
    Q = [r]
    L = []
    visited = set([r])
    while Q:
        vn = Q.pop()
        L.append(vn)
        for vf in E[vn]:
            if vf not in visited:
                visited.add(vf)
                Q.append(vf)
    return L

def getcld(p):
    res = [[] for _ in range(len(p))]
    for i, v in enumerate(p[1:], 1):
        res[v].append(i)
    return res


        

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

P = getpar(Edge, 0)
L = topological_sort_tree(Edge, 0)
C = getcld(P)

dp1 = [0]*N

for q in range(Q):
    p, x = map(int, sys.stdin.readline().split())
    dp1[p-1] += x

for l in L:
    d = dp1[l]
    for c in C[l]:
        dp1[c] += d

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

Submission status: Accepted

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

e_list = [[] for i in range(N)]

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

add_list = [0]*N

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

count_list = [0]*N
count_list[0] = add_list[0]

vi = 0 #時と場合によってここを変える
from collections import deque
Q = deque([vi])
checked_list = [False for i in range(N)]
checked_list[vi]=True
while len(Q)>0:
    v = Q.pop()
    for v1 in e_list[v]:
        if not checked_list[v1]:
            checked_list[v1]=True
            Q.append(v1)
            count_list[v1] = count_list[v]+add_list[v1]

print(*count_list)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

from collections import defaultdict, Counter, deque
from operator import itemgetter
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)
def inpl(): return list(map(int, input().split()))

N, Q = inpl()
G = [[] for _ in range(N)]

for _ in range(N-1):
    a, b = inpl()
    G[a-1].append(b-1)
    G[b-1].append(a-1)

S = [0]*N
for _ in range(Q):
    x, d = inpl()
    S[x-1] += d

searched = [0]*N
searched[0] = True
Q = deque([0])

while Q:
    p = Q.popleft()
    for q in G[p]:
        if searched[q]:
            continue
        searched[q] = True
        S[q] += S[p]
        Q.append(q)

print(*S)

Submission status: Accepted

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

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

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

memo = [0] * n

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

def dfs(v, par):
    for nv in g[v]:
        if nv == par:
            continue
        memo[nv] += memo[v]
        dfs(nv, v)

dfs(0, -1)

print(*memo)

Submission status: Accepted

Solution code:
N,Q = map(int,input().split())
AB = [tuple(map(int,input().split())) for i in range(N-1)]
PX = [tuple(map(int,input().split())) for i in range(Q)]

es = [[] for i in range(N)]
for a,b in AB:
    a,b = a-1,b-1
    es[a].append(b)
    es[b].append(a)

xs = [0] * N
for p,x in PX:
    xs[p-1] += x

ans = [0] * N
ans[0] = xs[0]
visited = [0] * N
stack = [0]
while stack:
    v = stack.pop()
    visited[v] = 1
    for to in es[v]:
        if visited[to]: continue
        stack.append(to)
        ans[to] = ans[v] + xs[to]

print(*ans)

Submission status: Accepted

Solution code:
N,Q=map(int,input().split())
G=[[] for i in range(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)
X=[0 for i in range(N)]
for i in range(Q):
    p,x=map(int,input().split())
    X[p-1]+=x
q=[0]
reached=[0 for i in range(N)]
ans=[0 for i in range(N)]
#print(X)
while(len(q)>0):
    r=q.pop()
    ans[r]+=X[r]
    reached[r]=1
    for p in G[r]:
        if reached[p]==0:
            ans[p]+=ans[r]
            q.append(p)
print(*ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(300000)


def solve(N: int, Q: int, a: "List[int]", b: "List[int]", p: "List[int]", x: "List[int]"):
    conn = [[] for _ in range(N)]
    for i in range(N - 1):
        conn[a[i] - 1].append(b[i] - 1)
        conn[b[i] - 1].append(a[i] - 1)
    plus = [0] * N
    for i in range(Q):
        plus[p[i] - 1] += x[i]

    ret = [0] * N
    def dfs(idx, cur, visited):
        visited[idx] = True
        cur += plus[idx]
        ret[idx] = cur
        for nex in conn[idx]:
            if not visited[nex]:
                dfs(nex, cur, visited)
        return
    visited = [False] * N
    dfs(0, 0, visited)
    print(' '.join([str(r) for r in ret]))
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    Q = int(next(tokens))  # type: int
    a = [int()] * (N-1)  # type: "List[int]" 
    b = [int()] * (N-1)  # type: "List[int]" 
    for i in range(N-1):
        a[i] = int(next(tokens))
        b[i] = int(next(tokens))
    p = [int()] * (Q)  # type: "List[int]" 
    x = [int()] * (Q)  # type: "List[int]" 
    for i in range(Q):
        p[i] = int(next(tokens))
        x[i] = int(next(tokens))
    solve(N, Q, a, b, p, x)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import bisect
import heapq
import itertools
import math
import operator
import os
import re
import string
import sys
from collections import Counter, deque, defaultdict
from copy import deepcopy
from decimal import Decimal
from fractions import gcd
from functools import lru_cache, reduce
from operator import itemgetter, mul, add, xor

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

N, Q = list(map(int, sys.stdin.readline().split()))
AB = [list(map(int, sys.stdin.readline().split())) for _ in range(N - 1)]
PX = [list(map(int, sys.stdin.readline().split())) for _ in range(Q)]

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

counts = defaultdict(int)
for p, x in PX:
    counts[p] += x

ans = [0] * (N + 1)
ans[1] = counts[1]
que = deque([1])
while que:
    v = que.popleft()
    cnt = ans[v]
    for u in graph[v]:
        que.append(u)
        ans[u] = counts[u] + cnt

print(*ans[1:])

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)

used = [True]*n
used[0] = False

new = [0]
tank = []

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

while len(new) != 0:
    tank = []
    for e in new:
        for p in edge[e]:
            if used[p]:
                s[e].append(p)
                tank.append(p)
                used[p] = False 

    new = tank


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

new = [0]
tank = []
while len(new) != 0:
    tank = []
    for e in new:
        for p in s[e]:
            res[p] += res[e]
            tank.append(p)
    new = tank
for ans in res:
    print(ans,end = ' ')

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
from collections import deque
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)
Q=[0]*n
for _ in range(q):
    p,x=map(int,input().split())
    Q[p-1]+=x
Ans=[0]*n
q=deque([0])
Ans[0]=Q[0]
Visited=[False]*n
Visited[0]=True
while q:
    fr=q.pop()
    for to in Edges[fr]:
        if Visited[to]:
            continue
        Ans[to]=Ans[fr]+Q[to]
        Visited[to]=True
        q.append(to)
print(*Ans)

Submission status: Accepted

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


N,Q=map(int,input().split())
EDGE=[list(map(int,input().split())) for i in range(N-1)]
PLUS=[list(map(int,input().split())) for i in range(Q)]

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

ELIST=[[] for i in range(N+1)]

for x,y in EDGE:
    ELIST[x].append(y)
    ELIST[y].append(x)

from collections import deque
Q=deque([1])

USED=[0]*(N+1)
USED[1]=1

while Q:
    x=Q.pop()

    for to in ELIST[x]:
        if USED[to]==0:
            USED[to]=1
            SCORE[to]+=SCORE[x]
            Q.append(to)

print(*SCORE[1:])

Submission status: Runtime Error

Solution code:
def main():
    N, Q = map(int, input().split())
    child_parent = {}
    for _ in range(N-1):
        a, b = map(int, input().split())
        child_parent[b-1] = a-1
    cost = [0] * N
    for _ in range(Q):
        p, x = map(int, input().split())
        cost[p-1] += x
    for i in range(1, N):
        cost[i] += cost[child_parent[i]]
    print(' '.join([str(v) for v in cost]))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

# to enable variable use in global
global tree, point

# v : current node, f : parent node 
def dfs(v, f):
    for next_v in tree[v]:
        if next_v == f:
            continue
    
        point[next_v] += point[v]
        dfs(next_v, v)

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

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

dfs(0, 0)
print(*point)

Submission status: Runtime Error

Solution code:
n , q = map(int, input().split())
tree = [[] for _ in range(n)]
point = [0] * n
for _ in range(n - 1):
    a , b = map(int,input().split())
    tree[b - 1].append(a - 1)
    tree[a - 1].append(b - 1)

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

# v : current node, f : parent node 
def dfs(v, f):
    for next_v in tree[v]:
        if next_v == f:
            continue
    
        point[next_v] += point[v]
        dfs(next_v, v)

dfs(0, 0)
print(*point)

Submission status: Runtime Error

Solution code:
# to enable variable use in global
global tree, point

# v : current node, f : parent node 
def dfs(v, f):
    global tree, point
    for next_v in tree[v]:
        if next_v == f:
            continue
    
        point[next_v] += point[v]
        dfs(next_v, v)

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

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

dfs(0, 0)
print(*point)

Submission status: Runtime Error

Solution code:
# to enable variable use in global
global tree, point

# v : current node, f : parent node 
def dfs(v, f):
    global tree, point
    for next_v in tree[v]:
        if next_v == f:
            continue
    
        point[next_v] += point[v]
        dfs(next_v, v)

n, q = list(map(int,input().split()))
# initialize global variables
tree = [[]*n for i in range(n)]
point = [0] * n

for _ in range(n-1):
    a, b = list(map(int, input().split()))

    tree[a-1].append(b-1)
    tree[b-1].append(a-1)

for _ in range(q):
    p, x = list(map(int, input().split()))

    point[p-1] += x

dfs(0, 0)
print(*point)

Submission status: Runtime Error

Solution code:
# to enable variable use in global
global tree, point

# v : current node, f : parent node 
def dfs(v, f):
    for next_v in tree[v]:
        if next_v == f:
            continue
    
        point[next_v] += point[v]
        dfs(next_v, v)

n, q = list(map(int,input().split()))
# initialize global variables
tree = [[]*n for i in range(200010)]
point = [0] * n

for _ in range(n-1):
    a, b = list(map(int, input().split()))

    tree[a-1].append(b-1)
    tree[b-1].append(a-1)

for _ in range(q):
    p, x = list(map(int, input().split()))

    point[p-1] += x

dfs(0, 0)
print(*point)

Submission status: Runtime Error

Solution code:
# to enable variable use in global
global tree, point

# v : current node, f : parent node 
def dfs(v, f):
    for next_v in tree[v]:
        if next_v == f:
            continue
    
        point[next_v] += point[v]
        dfs(next_v, v)

n, q = list(map(int,input().split()))
# initialize global variables
tree = [[]*n for i in range(n)]
point = [0] * n

for _ in range(n-1):
    a, b = list(map(int, input().split()))

    tree[a-1].append(b-1)
    tree[b-1].append(a-1)

for _ in range(q):
    p, x = list(map(int, input().split()))

    point[p-1] += x

dfs(0, 0)
print(*point)

Submission status: Runtime Error

Solution code:
# to enable variable use in global
global tree, point

# v : current node, f : parent node 
def dfs(v, f):
    for next_v in tree[v]:
        if next_v == f:
            continue
    
        point[next_v] += point[v]
        dfs(next_v, v)

n, q = list(map(int,input().split()))
# initialize global variables
tree = [[] for i in range(n)]
point = [0] * n

for _ in range(n-1):
    a, b = list(map(int, input().split()))

    a -= 1
    b -= 1
    tree[a].append(b)
    tree[b].append(a)

for _ in range(q):
    p, x = list(map(int, input().split()))

    p -= 1
    point[p] += x

dfs(0, 0)
print(*point)

Submission status: Runtime Error

Solution code:
#!/usr/bin/python3
# coding: utf-8

from collections import defaultdict, deque

N, Q = (int(x) for x in input().split())
G = defaultdict(list)

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

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

def dfs(node, accum):
    ret[node] += accum
    for n in G[node]:
        dfs(n, ret[node])

dfs(0, 0)

print(" ".join(str(x) for x in ret))

Submission status: Runtime Error

Solution code:
#!/usr/bin/python3
# coding: utf-8

from collections import defaultdict

N, Q = (int(x) for x in input().split())
G = defaultdict(list)

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

ret = [0] * N


def dfs(p, x):
    ret[p] += x
    for n in G[p]:
        dfs(n, x)


for i in range(Q):
    p, x = (int(x) for x in input().split())
    dfs(p-1, x)

print(" ".join(str(x) for x in ret))

Submission status: Runtime Error

Solution code:
class Node:
    def __init__(self, index):
        self.index = index
        self.leaf = set()
        self.score = 0

    def set_parent(self, parent):
        self.leaf.remove(parent)
        for l in self.leaf:
            tree[l].set_parent(self.index)

    def add_score(self, score):
        self.score += score
        for l in self.leaf:
            tree[l].add_score(score)


N, Q = map(int, input().split())
print(N, Q)
# tree = {i: Node(i) for i in range(1, N + 1)}
tree = {}
for i in range(1, N+1):
    tree[i] = Node(i)
print(len(tree))
tree[1].leaf.add(1)
for i in range(N-1):
    n1, n2 = map(int, input().split())
    tree[n1].leaf.add(n2)
    tree[n2].leaf.add(n1)

tree[1].set_parent(1)

for _ in range(Q):
    p, x = map(int, input().split())
    tree[p].add_score(x)

print(' '.join([str(t.score) for t in tree.values()]))

Submission status: Runtime Error

Solution code:
class Node:
    def __init__(self, index):
        self.index = index
        self.leaf = set()
        self.score = 0

    def set_parent(self, parent):
        self.leaf.remove(parent)
        for l in self.leaf:
            tree[l].set_parent(self.index)

    def add_score(self, score):
        self.score += score
        for l in self.leaf:
            tree[l].add_score(score)


N, Q = map(int, input().split())
tree = {i: Node(i) for i in range(1, N+1)}
tree[1].leaf.add(1)
tmp = [tuple(map(int, input().split())) for _ in range(N-1)]
for i in range(len(tmp)):
    n1, n2 = tmp[i][0], tmp[i][1]
    tree[n1].leaf.add(n2)
    tree[n2].leaf.add(n1)

tree[1].set_parent(1)

for p, x in [tuple(map(int, input().split())) for _ in range(Q)]:
    tree[p].add_score(x)

print(' '.join([str(t.score) for t in tree.values()]))

Submission status: Runtime Error

Solution code:
import numpy as np

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


class Node:
    def __init__(self, index):
        self.index = index
        self.leaf = set()
        self.score = 0

    def set_parent(self, parent):
        self.leaf.remove(parent)
        for l in self.leaf:
            tree[l].set_parent(self.index)

    def add_score(self, score):
        self.score += score
        for l in self.leaf:
            tree[l].add_score(score)


tree = {1: Node(1)}
tree[1].leaf.add(1)
for i in [tuple(map(int, input().split())) for _ in range(N-1)]:
    n1, n2 = i[0], i[1]
    if n1 not in tree:
        tree[n1] = Node(n1)
    if n2 not in tree:
        tree[n2] = Node(n2)
    tree[n1].leaf.add(n2)
    tree[n2].leaf.add(n1)

tree[1].set_parent(1)

for p, x in [tuple(map(int, input().split())) for _ in range(Q)]:
    tree[p].add_score(x)

print(' '.join([str(t.score) for t in tree.values()]))

Submission status: Runtime Error

Solution code:
import numpy as np

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


class Node:
    def __init__(self, parent):
        self.parent = parent
        self.leaf = []
        self.score = 0

    def add_score(self, score):
        self.score += score
        for l in self.leaf:
            l.add_score(score)


tree = {1: Node(None)}
tmp = np.array([list(map(int, input().split())) for _ in range(N-1)])
for i in np.argsort(tmp[:, 0]):
    p, c = tmp[i][0], tmp[i][1]
    if p not in tree:
        tree[p] = Node(None)
    if c not in tree:
        tree[c] = Node(p)
    tree[p].leaf.append(tree[c])

for p, x in [tuple(map(int, input().split())) for _ in range(Q)]:
    tree[p].add_score(x)

print(' '.join([str(t.score) for t in tree.values()]))

Submission status: Runtime Error

Solution code:
import numpy as np

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


class Node:
    def __init__(self, parent):
        self.parent = parent
        self.leaf = []
        self.score = 0

    def add_score(self, score):
        self.score += score
        for l in self.leaf:
            l.add_score(score)


tree = {1: Node(None)}
tmp = np.array([list(map(int, input().split())) for _ in range(N-1)])
for i in np.argsort(tmp[:, 0]):
    p, c = tmp[i][0], tmp[i][1]
    if p not in tree:
        tree[p] = Node(None)
    if c not in tree:
        tree[c] = tree[p]
    tree[p].leaf.append(tree[c])

for p, x in [tuple(map(int, input().split())) for _ in range(Q)]:
    tree[p].add_score(x)

print(' '.join([str(t.score) for t in tree.values()]))

Submission status: Runtime Error

Solution code:
import numpy as np

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


class Node:
    def __init__(self, parent):
        self.parent = parent
        self.leaf = []
        self.score = 0

    def add_score(self, score):
        self.score += score
        for l in self.leaf:
            tree[l].add_score(score)


tree = {1: Node(None)}
tmp = np.array([list(map(int, input().split())) for _ in range(N-1)])
for i in np.argsort(tmp[:, 0]):
    p, c = tmp[i][0], tmp[i][1]
    if p not in tree:
        tree[p] = Node(None)
    tree[p].leaf.append(c)
    if c not in tree:
        tree[c] = Node(p)

for p, x in [tuple(map(int, input().split())) for _ in range(Q)]:
    tree[p].add_score(x)

print(' '.join([str(t.score) for t in tree.values()]))

Submission status: Runtime Error

Solution code:
import numpy as np

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


class Node:
    def __init__(self, parent):
        self.parent = parent
        self.leaf = []
        self.score = 0

    def add_score(self, score):
        self.score += x
        for l in self.leaf:
            tree[l].add_score(x)


tree = {1: Node(None)}
tmp = np.array([list(map(int, input().split())) for _ in range(N-1)])
for i in np.argsort(tmp[:, 0]):
    p, c = tmp[i][0], tmp[i][1]
    if p not in tree:
        tree[p] = Node(None)
    tree[p].leaf.append(c)
    if c not in tree:
        tree[c] = Node(p)

for p, x in [tuple(map(int, input().split())) for _ in range(Q)]:
    tree[p].add_score(x)

print(' '.join([str(t.score) for t in tree.values()]))

Submission status: Runtime Error

Solution code:
# 各頂点ごとに所属する木の大きさを計算する
N,Q = map(int,input().split())

E = [[] for _ in range(N+1)]
visited = [False for _ in range(N+1)]
Node_len = [1 for _ in range(N+1)]

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

AS = [0 for i in range(N+1)]
def dfs(node,parent=-1):
    for child in E[node]:
        if child == parent:
            continue
        AS[child] += AS[node]
        dfs(child,node)

for q in range(Q):
    p,x = map(int,input().split())
    AS[p] += x

dfs(1)
print(*AS[1:])

Submission status: Runtime Error

Solution code:
def dfs(v,prev = -1):
    for u in graph[v]:
        if u == prev:
            continue
        point[u] += point[v]
        dfs(u,v)

N, Q = list(map(int,input().split()))
graph = [[] for _ in range(N)]
point = [0]*N

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

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

dfs(0)
print(*point)

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
i4 = np.int32

if sys.argv[-1] == 'ONLINE_JUDGE':
    adjacency_list = '''
import numpy as np
from numba import njit
from collections import namedtuple

AdjacencyList = namedtuple('AdjacencyList', ['v', 'adj'])

@njit
def adjacency_list(n, a):
    """
    隣接リストの作成
    :param n: vertex の数
    :param a: 2d の ndarray, 各行は、[u, v] u: Edge の始点、v: Edge の終点
    :return: AdjacencyList
    """
    v = np.zeros(n + 1, np.int32)
    for i in range(a.shape[0]):
        v[a[i, 0] + 1] += 1
    for i in range(1, v.shape[0]):
        v[i] += v[i - 1]
    adj = np.empty(a.shape[0], np.int32)
    temp = np.zeros(n, np.int32)
    for i in range(a.shape[0]):
        from_ = a[i, 0]
        adj[v[from_] + temp[from_]] = a[i, 1]
        temp[from_] += 1
    return AdjacencyList(v, adj)


@njit
def at(gc, n):
    return gc.adj[gc.v[n]:gc.v[n + 1]]


@njit
def iter(gc, n):
    for i in range(gc.v[n], gc.v[n + 1]):
        yield gc.adj[i]        
    '''
    import os
    os.makedirs('nbacl/graphs', exist_ok=True)
    with open('nbacl/graphs/adjacency_list.py', 'w') as f:
        f.write(adjacency_list)

    abc138_d_numba = '''
import numpy as np
import nbacl.graphs.adjacency_list as tree
from numba import njit
from numba.types import Array, int32
from numba.pycc import CC
i4 = np.int32
cc = CC('abc138_d_numba')


# @njit((int32, int32, Array(int32, 1, 'C'), Array(int32, 1, 'C'), Array(int32, 1, 'C'), Array(int32, 1, 'C')))
@njit
def dfs(d, prev, v, adj, u, val):
    y = val[d]
    for i in range(v[d], v[d + 1]):
        x = adj[i]
        if x == prev:
            continue
        val[x] = y + u[x]
        dfs(x, d, v, adj, u, val)


@cc.export('solve', (Array(int32, 2, 'C'), Array(int32, 2, 'C'), int32))
def solve(a, p, N):
    tr = tree.adjacency_list(N, a)
    u = np.zeros(N, i4)
    val = np.zeros(N, i4)
    for i in range(p.shape[0]):
        u[p[i, 0] - 1] += p[i, 1]
    val[0] = u[0]
    dfs(0, -1, tr.v, tr.adj, u, val)
    return val


if __name__ == '__main__':
    cc.compile()
    '''
    with open('abc138_d_numba.py', 'w') as f:
        f.write(abc138_d_numba)
    import subprocess
    cmd = "python3.8 abc138_d_numba.py"
    subprocess.run(cmd.split())
    exit(0)


from abc138_d_numba import solve

def main():
    f = open(0)
    N, Q = [int(x) for x in f.readline().split()]
    ap = np.fromstring(f.read(), i4, sep=' ').reshape((-1, 2))
    a = ap[:N - 1] - 1
    a = np.concatenate((a, a[:, ::-1]))
    p = ap[N - 1:]
    val = solve(a, p, N)
    print(*val.tolist())


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n,q=map(int,input().split())
ans=[0 for _ in range(n)]
gra=[[] for _ in range(n)]
visited=[0 for _ in range(n)]
for _ in range(n-1):
  a,b=map(int,input().split())
  gra[a-1].append(b-1)
  gra[b-1].append(a-1)
  
for _ in range(q):
  p,x=map(int,input().split())
  ans[p-1]+=x
  
def dfs(st):
  temp=gra[st]
  for i in temp:
    if visited[i]==0:
      visited[i]+=1
      ans[i]+=ans[st]
      dfs(i)
      
visited[0]+=1
dfs(0)

for h in range(n):
  ans[h]=str(ans[h])
  
print(' '.join(ans))