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: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
inf = float('inf')
ninf = -float('inf')
 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

n,q=mii()
mat = [[] for _ in range(n)]

for i in range(n-1):
    mat[a-1].append(b-1)

cnt=[0]*n

for i in range(q):
    p,x=mii()
    cnt[p-1]+=x

ans=[0]*n

def dfs(point,now,parent):
    ans[now]+=point+cnt[now]

    for visit in mat[now]:
        if visit==parent:continue
        dfs(ans[now],visit,now)

print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np
N,Q = map(int,input().split())
t =  np.zeros((N+1,N+1))

ans = np.zeros(N+1)

for i in range(N-1):
    x,y = map(int,input().split())
    t[x,y] += 1
for i in range(N):
    t[i,i] = 1

for i in range(N,0,-1):
    t[i-1] += t[i]
#print(t)
t = (t>=1)
#print(t)
for i in range(Q):
    x,y = map(int,input().split())
    ans += y*t[x]
#print(ans)
for i in range(1,N+1):
    print(int(ans[i]), end=" ")

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys


class Node:
    def __init__(self, num):
        self.num = num
        self.ct = 0
        self.temp_ct = 0
        self.edge = []
    
    def set_temp_ct(self, ct_):
        self.temp_ct += ct_
    
    def set_ct(self, ct):
        self.ct = self.temp_ct + ct
        return self.ct

    def set_edge(self, e):
        self.edge.append(e)

    def pop_edge(self, e):
        if e in self.edge:
            self.edge.remove(e)



def solve(N: int, Q: int, a: "List[int]", b: "List[int]", p: "List[int]", x: "List[int]"):
    nodes = [Node(num+1) for num in range(N)]
    for qa, qb in zip(a,b):
        nodes[qa-1].set_edge(qb)
        nodes[qb-1].set_edge(qa)

    for qp, qx in zip(p, x):
        nodes[qp-1].set_temp_ct(qx)

    def d_node(num, pre_ct):
        pre_ct = nodes[num-1].set_ct(pre_ct)
        for ls in nodes[num-1].edge:
            nodes[ls-1].pop_edge(num)
            d_node(ls, pre_ct)
    
    d_node(1, 0)

    a = [nodes[x].ct for x in range(N)]
    print(*a)


    return


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys


class Node:
    def __init__(self, num):
        self.num = num
        self.ct = 0
        self.temp_ct = 0
        self.edge = []

    def set_leaf(self, leaf):
        self.leaf = leaf
    
    def set_temp_ct(self, ct_):
        self.temp_ct += ct_
    
    def set_ct(self, ct):
        self.ct = self.temp_ct + ct
        return self.ct

    def set_edge(self, e):
            self.edge.append(e)

    def pop_edge(self, e):
            self.edge.remove(e)



def solve(N: int, Q: int, a: "List[int]", b: "List[int]", p: "List[int]", x: "List[int]"):
    nodes = [Node(num+1) for num in range(N)]
    for qa, qb in zip(a,b):
        nodes[qa-1].set_edge(qb)
        nodes[qb-1].set_edge(qa)

    for qp, qx in zip(p, x):
        nodes[qp-1].set_temp_ct(qx)

    def d_node(num, pre_ct):
        pre_ct = nodes[num-1].set_ct(pre_ct)
        for ls in nodes[num-1].edge:
            nodes[ls-1].pop_edge(num)
            d_node(ls, pre_ct)
    
    d_node(1, 0)

    a = [nodes[x].ct for x in range(N)]
    print(*a)


    return


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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: Runtime Error

Solution code:
# 初期入力
import numpy as np 
N,Q = (int(x) for x in input().split())
aa=0  
bb=0
a=[0] 
b=[0]
ki_kouzou =np.zeros((N+1,N+1),dtype=int)

for i in range(1,N): #木の構造を入力
    aa,bb = (int(x) for x in input().split())
    ki_kouzou[aa,bb] =1
    a.append(aa) 
    b.append(bb)

#葉から根に向かい構造足していく
for i in range(N-1,0,-1):
    ki_kouzou[a[i],:] +=ki_kouzou[b[i],:]

for i in range(1,N+1): #各頂点は必ずフラグ立つ
    ki_kouzou[i,i] =1

# ポイント入力
p=[] ; x=[]
pp=0 ; xx=0
for i in range(Q):
    pp,xx = (int(x) for x in input().split())
    p.append(pp)
    x.append(xx)

#ポイント計算
point =np.zeros((N+1),dtype=int)
for i in range(Q):
    point +=ki_kouzou[p[i]] *x[i]

print(*point[1:])

Submission status: Runtime Error

Solution code:
import sys
input=sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
n,q=map(int,input().split())
edges=[[] for i in range(n)]
inp=sys.stdin.buffer.readlines()
for i in inp[:n-1]:
    a,s=map(int,i.split());a-=1;s-=1
    edges[a].append(s)
    edges[s].append(a)
cnt=[-1]*n
add=[0]*n
for _ in inp[n-1:]:
    a,s=map(int,_.split())
    add[a-1]+=s


def f(x):
    if cnt[x]!=-1:return 0
    ret=add[x]
    fd=0
    for to in edges[x]:
        if cnt[to]!=-1:ret+=cnt[to];fd=to;break
    cnt[x]=str(ret)
    for to in edges[x]:
        if to!=fd:f(to)
    
    
f(0)
print(' '.join(cnt))

Submission status: Runtime Error

Solution code:
import sys
input=sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
n,q=map(int,input().split())
edges=[[] for i in range(n)]
inp=sys.stdin.buffer.readlines()
for i in inp[:n-1]:
    a,s=map(int,i.split());a-=1;s-=1
    edges[a].append(s)
    edges[s].append(a)
cnt=[-1]*n
add=[0]*n
for _ in inp[n-1:]:
    a,s=map(int,_.split())
    add[a-1]+=s


def f(x):
    if cnt[x]!=-1:return 
    ret=add[x]
    fd=0
    for to in edges[x]:
        if cnt[to]!=-1:ret+=cnt[to];fd=to;break
    cnt[x]=str(ret)
    for to in edges[x]:
        if to!=fd:f(to)
    
    
f(0)
print(' '.join(cnt))

Submission status: Runtime Error

Solution code:
n,q=map(int,input().split())
edges=[[] for i in range(n)]
for i in range(n-1):
    a,s=map(int,input().split());a-=1;s-=1
    edges[a].append(s)
    edges[s].append(a)
cnt=[-1]*n
add=[0]*n
for _ in range(q):
    a,s=map(int,input().split())
    add[a-1]+=s

def f(x):
    if cnt[x]!=-1:return cnt[x]
    ret=add[x]
    after=[]
    for to in edges[x]:
        if cnt[to]==-1:after.append(to)
        else:ret+=cnt[to]
    cnt[x]=ret
    for i in after:
        f(i)
    return 0
f(0)
print(*cnt,sep=" ")

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
ab = [list(map(lambda x:int(x)-1, input().split())) for _ in range(N-1)]
px = [list(map(lambda x:int(x)-1, input().split())) for _ in range(Q)]
graph = [[] for _ in range(N)]
for a, b in ab:
  graph[a] += [b]
dist = [0 for _ in range(N)]
for p, x in px:
  dist[p] += x+1

def dfs(u, pre):
  for v in graph[u]:
    if v != pre:
      dist[v] += dist[u]
      dfs(v, u)

  return 

dfs(0, -1)
dist = list(map(str, dist))
print(" ".join(dist))

Submission status: Runtime Error

Solution code:
import sys
def LI(): return [int(x) for x in sys.stdin.readline().split()]

n,q = LI()

v = [[] for i in range(n)]
for i in range(n-1):
  a,b = LI()
  a -= 1 # listのindex参照をそのまま使いたいので頂点id(1から始まっている)を-1しておく
  b -= 1 # aと同様
  v[a].append(b)
  v[b].append(a)

f = [0]*n
for i in range(q):
  p,x = LI()
  p -= 1 # aと同様
  f[p] += x

def dfs(x,d,s): # x:計算する頂点（上側）, d:計算済み(0)か否か(1), s:頂点xの値
  for y in v[x]: # 頂点xとつながる各頂点yの計算を行う
    if d[y]: # 頂点yが計算未了の場合
      s += f[y] # 頂点xの値sに頂点yの値を足す
      ans[y] = s # 頂点yの値はsに確定
      d[y] = 0 # 頂点yの計算は終わったのでd[y]=0とする
      dfs(y,d,s) # 頂点yの下層についても再帰的に計算
      s -= f[y] # 頂点yの下層の計算が終わったので、sを頂点xの値に戻す

ans = [0]*n
d = [1]*n
d[0] = 0
ans[0] = f[0]
s = f[0]
dfs(0,d,s)
print(*ans)

Submission status: Runtime Error

Solution code:
n, q = map(int, input().split())
connect = [[] for _ in range(n)]
for _ in range(n-1):
    a, b = map(int, input().split())
    connect[a - 1].append(b-1)
    connect[b - 1].append(a - 1)
    
values = [0] * n
for _ in range(q):
    p, x = map(int, input().split())
    values[p - 1] += x

def dfs(parent, flags, add_num):
    for num in connect[parent]:
        if flags[num]:
            add_num += values[num]
            result[num] = add_num
            flags[num] = 0
            dfs(num, flags, add_num)
            add_num -= values[num]
result = [0] * n
result[0] = values[0]
flags = [1] * n
flags[0] = 0
add_num = values[0]
dfs(0, flags, add_num)
print(' '.join(str(i) for i in result))

Submission status: Runtime Error

Solution code:
n, q = map(int, input().split())
connect = [[] for _ in range(n)]
for _ in range(n-1):
    a, b = map(int, input().split())
    connect[a - 1].append(b-1)
    connect[b - 1].append(a-1)
values = [0] * n
for _ in range(q):
    p, x = map(int, input().split())
    values[p - 1] += x
result = [values[0]] + [0] * (n - 1)
flags = [0] + [1] * (n - 1)
def dfs(parent, flags, add_num):
    for num in connect[parent]:
        if flags[num]:
            add_num += values[num]
            result[num] = add_num
            flags[num] = 0
            dfs(num, flags, add_num)
            add_num -= values[num]
dfs(0, flags, values[0])
print(' '.join(str(i) for i in result))

Submission status: Runtime Error

Solution code:
def dfs(G,v,p):
    for nv in G[v]:
        if(nv==p):
            continue
        point[nv]+=point[v]
        dfs(G,nv,v)

N,Q=map(int,input().split())
G=[[] for i in range(N)]
for i in range(N-1):
    a,b=map(lambda x:int(x)-1,input().split())
    G[a].append(b)
    G[b].append(a)
point=[0]*N
for i in range(Q):
    p,x=map(int,input().split())
    point[p-1]+=x
dfs(G,0,-1)
print(*point)

Submission status: Runtime Error

Solution code:
from collections import defaultdict
n, q = map(int, input().split())
child = defaultdict(list)
ns = set()
for i in range(n - 1):
    a, b = map(int, input().split())
    child[a].append(b)
    ns.add(a)
    ns.add(b)
cnt = defaultdict(int)
for i in range(q):
    p, x = map(int, input().split())
    cnt[p] += x
def dfs(i):
    for num in child[i]:
        cnt[num] += cnt[i]
        dfs(num)
dfs(1)
print(' '.join(str(value) for _, value in sorted(cnt.items(), key=lambda x: x[0])))

Submission status: Runtime Error

Solution code:
from collections import defaultdict
connect = defaultdict(list)
n, q = map(int, input().split())
for i in range(n - 1):
    a, b = map(int, input().split())
    connect[a].append(b)
sub = defaultdict(list)
def ki(key, root, dic):
    for i in dic[root]:
        sub[key].append(i)
        ki(key, i, dic)
for i in range(1, n+1):
    ki(i, i, connect)
for i in range(1, n+1):
    sub[i].append(i)
score = defaultdict(int)
for i in range(q):
    p, x = map(int, input().split())
    for num in sub[p]:
        score[num] += x
print(' '.join(str(j) for _, j in sorted(score.items(), key=lambda x: x[0])))

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
rela = [[] for i in range(N)]
for i in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    rela[a].append(b)
    rela[b].append(a)
hoge = [0] * N
for i in range(Q):
    p, x = map(int, input().split())
    p -= 1
    hoge[p] += x
from collections import deque
que = deque([0])
while que:
    cur = que.pop()
    for new in rela[cur]:
      	if new == cur:
          continue
        hoge[new] += hoge[cur]
        que.append(new)
print(*hoge)

Submission status: Runtime Error

Solution code:
import sys
f=lambda:map(int,sys.stdin.readline().split())
n,q=f()
g=[[] for _ in range(n)]
for i in range(n-1):
  a,b=f()
  g[a-1]+=[b-1]
  g[b-1]+=[a-1]
c=[0]*n
for i in range(q):
  v,x=f()
  c[v-1]+=x
def dfs(v,p=-1):
  for i in g[v]:
    if i==p: continue
    c[i]+=c[v]
    dfs(i,v)
dfs(0)
print(*c)

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
p = [0]*2*100000
e = [0]*2*100000
q = []
    
for i in range(1,N):
    tmpa, tmpb = map(int, input().split())
    if e[tmpb] > 0 or tmpb == 1:
        e[tmpa] = tmpb
    elif e[tmpa] > 0 or tmpa == 1:
        e[tmpb] = tmpa
    else:
        q.append([tmpa, tmpb])
while len(q) > 0:
    qtmp = []
    for [a,b] in q:
        if e[b] > 0:
            e[a] = b
        elif e[a] > 0:
            e[b] = a
        else:
            qtmp.append([a,b])
    q = qtmp
    
for i in range(1,Q+1):
    tmpp, tmpx = map(int, input().split())
    p[tmpp] = p[tmpp] + tmpx

res = []    
for i in range(1,N+1):
    v = 0
    tmp = i
    while tmp > 0:
        v = v + p[tmp]
        tmp = e[tmp]
        
    res.append(v)

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

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
p = [0]*2*100000
e = [0]*2*100000
         
    
for i in range(1,N):
    tmpa, tmpb = map(int, input().split())
    if e[tmpb] == 0:
	    e[tmpb] = tmpa
    elif e[tmpa] == 0:
        e[tmpa] = tmpb


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

res = []    
for i in range(1,N+1):
    v = 0
    tmp = i
    while tmp > 0:
        v = v + p[tmp]
        tmp = e[tmp]
        
    res.append(v)

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

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
p = [0]*2*100000
e = [0]*2*100000
         
    
for i in range(1,N):
    tmpa, tmpb = map(int, input().split())
    e[tmpb] = tmpa

e[1] = 0

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

res = []    
for i in range(1,N+1):
    v = 0
    tmp = i
    while tmp > 0:
        v = v + p[tmp]
        tmp = e[tmp]
    res.append(v)

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

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
p = {}
e = {}
         
    
for i in range(1,N):
    tmpa, tmpb = map(int, input().split())
    e[tmpb] = tmpa

e[1] = 0

for i in range(1,Q+1):
    tmpp, tmpx = map(int, input().split())
    if tmpp in p:
        p[tmpp] = p[tmpp] + tmpx
    else:
        p[tmpp] = tmpx

res = []    
for i in range(1,N+1):
    v = 0
    tmp = i
    while tmp > 0:
        if tmp in p:
            v = v + p[tmp]
        tmp = e[tmp]
    res.append(v)

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

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
a = []
b = []
p = {}
e = {}
         
    
for i in range(1,N):
    tmpa, tmpb = map(int, input().split())
    a.append(tmpa)
    b.append(tmpb)
    e[tmpb] = tmpa

e[1] = 0

for i in range(1,Q+1):
    tmpp, tmpx = map(int, input().split())
    if tmpp in p:
        p[tmpp] = p[tmpp] + tmpx
    else:
        p[tmpp] = tmpx

res = []    
for i in range(1,N+1):
    v = 0
    tmp = i
    while tmp > 0:
        if tmp in p:
            v = v + p[tmp]
        tmp = e[tmp]
    res.append(v)

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

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
a = []
b = []
p = {}
e = {}
r = {}
def trv(start, v):
    if start in p:
        v = v + p[start]
    r[start] = v
    if start in e:
        el = e[start]
        for k in el:
            trv(k, v)
            
    
for i in range(1,N):
    tmpa, tmpb = map(int, input().split())
    a.append(tmpa)
    b.append(tmpb)
    if tmpa in e:
        e[tmpa].append(tmpb)
    else:
        e[tmpa] = [tmpb]
    
for i in range(1,Q+1):
    tmpp, tmpx = map(int, input().split())
    if tmpp in p:
        p[tmpp] = p[tmpp] + tmpx
    else:
        p[tmpp] = tmpx
for i in range(1,N+1):
    r[i] = 0
    
trv(1, 0)
res = []
for i in range(1,N+1):
    res.append(r[i])
print(' '.join(map(str, res)))

Submission status: Runtime Error

Solution code:
N,Q=map(int,input().split())
graph=[[]for _ in range(N)]
point=[0]*N
for _ in range(N-1):
    a,b=map(int,input().split())
    graph[a-1].append(b-1)
    graph[b-1].append(a-1)
for _ in range(Q):
    a,b=map(int,input().split())
    a=a-1
    point[a]=point[a]+b

def dfs(now,prev=-1):
    for next in graph[now]:
        if next==prev:
            continue
        point[next]=point[next]+point[now]
        dfs(next,now)
dfs(0)
print(*point)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10000)

n,q = map(int,input().split())
points = [0]*(n+1)
tree = [[] for _ in range(n+1)]
for i in range(n-1):
    l, m = map(int,input().split())
    tree[l].append(m)

def dfs(e,p):
    points[e] += p
    for i in tree[e]:
        dfs(i,p)


for i in range(q):
    e, p = map(int, input().split())
    dfs(e,p)
print(*points[1:])
# print(tree)

Submission status: Runtime Error

Solution code:
n,q = map(int,input().split())
points = [0]*(n+1)
tree = [[] for _ in range(n+1)]
for i in range(n-1):
    l, m = map(int,input().split())
    tree[l].append(m)

def dfs(e,p):
    points[e] += p
    for i in tree[e]:
        dfs(i,p)


for i in range(q):
    e, p = map(int, input().split())
    dfs(e,p)
print(*points[1:])
# print(tree)

Submission status: Runtime Error

Solution code:
import os, sys, re, math, queue
sys.setrecursionlimit(100000)
N,Q = list(map(int,input().split(' ')))

nodes = {}

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

ret = [0 for i in range(N)]

for _ in range(Q):
    p,q = list(map(int,input().split(' ')))
    p -= 1
    ret[p] += q

def add_cnt(p):
    if p in nodes:
        for t in nodes[p]:
            ret[t] += ret[p]
            add_cnt(t)

add_cnt(0)

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

Submission status: Runtime Error

Solution code:
import os, sys, re, math, queue
sys.setrecursionlimit(100000)
N,Q = list(map(int,input().split(' ')))

nodes = {}

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

ret = [0 for i in range(N)]

for _ in range(Q):
    p,q = list(map(int,input().split(' ')))
    p -= 1
    ret[p] += q

def add_cnt(p):
    if p in nodes:
        for t in nodes[p]:
            ret[t] += ret[p]
            add_cnt(t)

add_cnt(0)

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

Submission status: Runtime Error

Solution code:
import os, sys, re, math, queue
sys.setrecursionlimit(100000)
N,Q = list(map(int,input().split(' ')))

nodes = {}

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

nodes_cnt = [0 for i in range(N)]

for _ in range(Q):
    p,q = list(map(int,input().split(' ')))
    p -= 1
    nodes_cnt[p] += q

def add_cnt(root,point):
    nodes_cnt[root] += point
    if root in nodes:
        tmp = nodes[root]
        for t in tmp:
            add_cnt(t, nodes_cnt[root])

add_cnt(0, 0)

nodes_cnt = map(str,nodes_cnt)
print(' '.join(nodes_cnt))

Submission status: Runtime Error

Solution code:
import os, sys, re, math, queue
sys.setrecursionlimit(100000)
N,Q = list(map(int,input().split(' ')))

nodes = {}

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

nodes_cnt = [0 for i in range(N)]
ret = [0 for i in range(N)]

for _ in range(Q):
    p,q = list(map(int,input().split(' ')))
    p -= 1
    nodes_cnt[p] += q

def add_cnt(root,point):
    ret[root] += point
    if root in nodes:
        tmp = nodes[root]
        for t in tmp:
            add_cnt(t, point)

for i in range(N):
    if nodes_cnt[i] > 0:
        add_cnt(i, nodes_cnt[i])

ret = map(str,ret)
print(' '.join(ret))

Submission status: Runtime Error

Solution code:
import os, sys, re, math, queue

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

nodes = {}

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

nodes_cnt = [0 for i in range(N)]
ret = [0 for i in range(N)]

for q in range(Q):
    p,q = list(map(int,input().split(' ')))
    p -= 1
    nodes_cnt[p] += q

def add_cnt(root,point):
    ret[root] += point
    if root in nodes:
        tmp = nodes[root]
        for t in tmp:
            add_cnt(t, point)

for i in range(N-1):
    if nodes_cnt[i] > 0:
        add_cnt(i, nodes_cnt[i])

ret = map(str,ret)
print(' '.join(ret))

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline
from itertools import permutations,  combinations, accumulate
from functools import *
from collections import deque, defaultdict, Counter
from heapq import heapify, heappop, heappush, heappushpop

INF = float('inf')
NIL = - 1


class Node:
    def __init__(self, parent, left):
        """
        Left-child, Right-sibiling
        """
        self.parent = parent
        self.left = left
        self.right = []
        self.point = 0

    def __str__(self):
        return f'parent = {self.parent}, left = {self.left}, right = {self.right}, point = {self.point}'


def set_point(T, node, point):
    T[node].point += point

    if T[node].left != NIL:
        l_child = T[node].left
        set_point(T, l_child, point)
        # T[l_child].point += point

    if T[node].right:
        for idx in range(len(T[node].right)):
            r_child = T[node].right[idx]
            set_point(T, r_child,  point)
            # T[r_child].point += point


N, Q = map(int, input().split())
T = {k: Node(NIL, NIL) for k in range(N)}

for i in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    if T[a].left == NIL:
        left_child = b
        T[a].left = left_child
        T[left_child].parent = a
    else:
        T[a].right.append(b)
        T[b].parent = a

# for i in range(N):
#     print(i, T[i])

for j in range(Q):
    p, x = map(int, input().split())
    p -= 1
    set_point(T, p, x)


scores = []
for i in range(N):
    scores.append(T[i].point)

print(*scores)

# def main():


# if __name__ == '__main__':
#     main()

Submission status: Runtime Error

Solution code:
N,Q= map(int, input().split())
d = {}
counter = [0]*N
for i in range(N-1):
    key, value = input().split()
    if key in d.keys():
        d[key] += value
    else:
        d[key] = value

def fun_dict(key):
    temp = len(d[key])
    for i in range(temp):
        if d[key][i] in d.keys():
            d[key] += d[d[key][i]]
            fun_dict(d[key][i])
fun_dict('1')

for i in range(Q):
    p, x = map(int, input().split())
    counter[p-1] += x
    if str(p) in d.keys():
        for values in d[str(p)]:
            counter[int(values) - 1] += x
print(' '.join(map(str, counter)))

Submission status: Runtime Error

Solution code:
N,Q= map(int, input().split())
d = {}
counter = [0]*N
for i in range(N-1):
    key, value = input().split()
    if key in d.keys():
        d[key] += value
    else:
        d[key] = value

def fun_dict(key):
    temp = len(d[key])
    for i in range(temp):
        if d[key][i] in d.keys():
            d[key] += d[d[key][i]]
            fun_dict(d[key][i])
fun_dict('1')

for i in range(Q):
    p, x = map(int, input().split())
    counter[p-1] += x
    if str(p) in d.keys():
        for values in d[str(p)]:
            counter[int(values) - 1] += x
print(list(map(str, counter)))
print(' '.join(map(str, counter)))

Submission status: Runtime Error

Solution code:
from collections import deque
n,q = map(int,input().split())
graph = [[] for _ in range(n)]
cnt = [0] * n
already = [False] * n

for i in range(n-1):
    a,b = map(int,input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)
    
for i in range(q):
    p,x = map(int,input().split())
    cnt[p-1] += x
wait_q = deque()
wait_q.append(0)

while len(wait_q) > 0:
    parent = wait_q.popleft()
    already[child] = True
    for child in graph[parent]:
        if child == 0:continue
        if already[child] == True:continue
        cnt[child] += cnt[parent]
        wait_q.append(child)
print(*cnt)

Submission status: Runtime Error

Solution code:
n,q = map(int,input().split())

from collections import defaultdict
dic = defaultdict(list)


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


dic2 = defaultdict(int)

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

ansl = [0 for i in range(n)]
used = [-1 for i in range(n)]
used[0] = 1
def dfs(pos):
    for p in dic[pos]:
        if used[p] == -1:
            ansl[p] = ansl[pos] + dic2[pos]
            used[p] = 1
            dfs(p)

dfs(0)
for idx, a in enumerate(ansl):
    print(a + dic2[idx])

Submission status: Runtime Error

Solution code:
import math
import collections
from operator import mul
from functools import reduce
import bisect
import string
import copy

l = [[] for i in range(200005)]

def unit(a,b):
    l[a].append(b)
    l[b].append(a)

def search(a,b):
    for i in l[a]:
        if i!=b:
            y[i]+=y[a]
            search(i,a)


n,q=map(int,input().split())
y=[0]*n
for i in range(n-1):
    a,b=map(int,input().split())
    unit(a-1,b-1)

for i in range(q):
    a,b=map(int,input().split())
    y[a-1]+=b

search(0,-1)
 
for i in range(n):
    print(y[i])

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(2*(10**5)+1)
def main():
    input = sys.stdin.readline
    N, Q = map(int,input().split())
    T = [[] for k in range(N)]
    V = [0]*N
    for _ in range(N-1):
        a, b = map(int,input().split())
        T[a-1].append(b-1)
        T[b-1].append(a-1)
    for q in range(Q):
        p, x = map(int,input().split())
        V[p-1] += x

    def dfs(mae,ima):
        for tsugi in T[ima]:
            if tsugi != mae:
                V[tsugi] += V[ima]
                dfs(ima,tsugi)
    dfs(-1,0)
    print(*V)
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**5+1)
N, Q = map(int,input().split())
T = [[] for k in range(N)]
V = [0]*N
for _ in range(N-1):
    a, b = map(int,input().split())
    T[a-1].append(b-1)
    T[b-1].append(a-1)
for q in range(Q):
    p, x = map(int,input().split())
    V[p-1] += x

def dfs(mae,ima):
    for tsugi in T[ima]:
        if tsugi != mae:
            V[tsugi] += V[ima]
            dfs(ima,tsugi)
dfs(-1,0)
print(*V)

Submission status: Runtime Error

Solution code:
N, Q = map(int,input().split())
T = [[] for k in range(N)]
V = [0]*N
for _ in range(N-1):
    a, b = map(int,input().split())
    T[a-1].append(b-1)
    T[b-1].append(a-1)
for q in range(Q):
    p, x = map(int,input().split())
    V[p-1] += x

def dfs(mae,ima):
    for tsugi in T[ima]:
        if tsugi != mae:
            V[tsugi] += V[ima]
            dfs(ima,tsugi)
dfs(-1,0)
print(*V)

Submission status: Runtime Error

Solution code:
n,q=map(int, input().split())
edges = [[]for _ in range(n)]
counter = [0]*n
done = [0]*n

for i in range(n-1):
    a,b=map(int, input().split())
    #頂点a, bのどちらが親か調べる 頂点1が根
    edges[a-1].append(b-1)



for i in range(q):
    a,b=map(int, input().split())
    counter[a-1]+=b

def dfs(i: int):
    for j in edges[i]:
        counter[j]+=counter[i]
        dfs(j)

dfs(0)
print(*counter)