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:
# from collections import deque
#
# N, Q = map(int, input().split())  # N個の頂点, Q回の操作
#
# # 辺を受け取る
# graph = [[] for _ in range(N)]
#
# for _ in range(N-1):
#     a, b = map(lambda x: int(x)-1, input().split())
#     graph[a].append(b)
#     graph[b].append(a)
#
# count = [0] * N
# # その頂点に対して与えられるカウントは伝播する
# for i in range(Q):  # Q個の操作について
#     p, x = map(int, input().split())
#     # ある頂点を根とする部分木には、今現在のcountが全て伝播していく
#     count[p-1] += x
#
# q = deque([0])  # 開始のノード
# flag = [False] * N
#
# while len(q):
#     v = q.pop()
#     flag[v] = True  # 部分木の根を到達済みにする
#
#     for e in graph[v]:  # vを根にもつノード全てに操作をする
#         # graphは子のみを格納するのではなく、そのノードから出ている辺を
#         # 親とか子供とか関係なく全て格納してしまうため、親の方向に
#         # 対して伝播をしないようにflagで管理する
#         if flag[e]:  # 頂点eがvの親であればスルー
#             continue
#         # eはvの子供であることが確定する
#         count[e] += count[v]  # 親の値を伝播させていく
#         q.append(e)
#
# print(*count)


#りゅうせいの解答（実行時エラー）
import numpy as np

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

ans = []
for k in range(N):
    ans.append(0)

#カウント用関数
def counting(ans,binary_tree,count_list, y, idy):
    ans[int(binary_tree[idy]) - 1] += y[1]
    if (binary_tree[idy*2 + 1] != 0):
        counting(ans, binary_tree, count_list, y, idy*2 + 1)

    if (binary_tree[idy*2 + 2] != 0):
        counting(ans, binary_tree, count_list, y, idy*2 + 2)


#treeの作成
binary_tree = np.zeros(2**(N+1))
binary_tree[0] = 1

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

while (len(tuple_list)):
    x = tuple_list.pop(0)
    idx = np.where(binary_tree == x[0])[0]

    if (binary_tree[idx*2 + 1] == 0):
        binary_tree[idx * 2 + 1] = x[1]

    else:
        binary_tree[idx * 2 + 2] = x[1]

#木の表示
#print(binary_tree)

count_list = [list(map(int,input().split())) for j in range(Q)]
while (len(count_list)):
    y = count_list.pop(0)
    idy = np.where(binary_tree == y[0])[0]
    counting(ans, binary_tree, count_list, y, idy)

strs = [str(num) for num in ans]
print(" ".join(strs))

Submission status: Runtime Error

Solution code:
import numpy as np

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

ans = []
for k in range(N):
    ans.append(0)

#カウント用関数
def counting(ans,binary_tree,count_list, y, idy):
    ans[int(binary_tree[idy]) - 1] += y[1]
    if (binary_tree[idy*2 + 1] != 0):
        counting(ans, binary_tree, count_list, y, idy*2 + 1)

    if (binary_tree[idy*2 + 2] != 0):
        counting(ans, binary_tree, count_list, y, idy*2 + 2)


#treeの作成
binary_tree = np.zeros(2**(N+1))
binary_tree[0] = 1

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

while (len(tuple_list)):
    x = tuple_list.pop(0)
    idx = np.where(binary_tree == x[0])[0]

    if (binary_tree[idx*2 + 1] == 0):
        binary_tree[idx * 2 + 1] = x[1]

    else:
        binary_tree[idx * 2 + 2] = x[1]

#木の表示
#print(binary_tree)

count_list = [list(map(int,input().split())) for j in range(Q)]
while (len(count_list)):
    y = count_list.pop(0)
    idy = np.where(binary_tree == y[0])[0]
    counting(ans, binary_tree, count_list, y, idy)

print(ans)

Submission status: Runtime Error

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

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

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)
    
check = [0] * (n+1)
count = [0] * (n+1)

for i in range(q):
    p,x = map(int,input().split())
    count[p] += x
    
def dfs(v):
  for u in g[v]:
    if check[u]==1:
      continue
    check[u]=1
    count[u]+=count[v]
    dfs(u)
 

check[1] = 1
dfs(1)

print(*count[1:])

Submission status: Runtime Error

Solution code:
import collections

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

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)
    
check = [0] * (n+1)
count = [0] * (n+1)

for i in range(q):
    p,x = map(int,input().split())
    count[p] += x
    
def dfs(v):
  for u in g[v]:
    if check[u]==1:
      continue
    check[u]=1
    count[u]+=count[v]
    dfs(u)
 

check[1] = 1
dfs(1)

print(*count[1:])

Submission status: Runtime Error

Solution code:
import collections

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

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)
    
check = [0] * (n+1)
count = [0] * (n+1)

for i in range(q):
    p,x = map(int,input().split())
    count[p] += x
    
def dfs(v):
  for u in g[v]:
    if check[u]==1:
      continue
    check[u]=1
    count[u]+=check[v]
    dfs(u)
 

check[1] = 1
dfs(1)

print(*count[1:])

Submission status: Runtime Error

Solution code:
import collections

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

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)
    
check = [0] * (n+1)
count = [0] * (n+1)

for i in range(q):
    p,x = map(int,input().split())
    count[p] += x
    
def dfs(x):
    check[x] = 1
    for u in g[x]:
        if check[u] == 1:
            continue
        count[u] += count[x]
        dfs(u)

check[1] = 1
dfs(1)

print(*count[1:])

Submission status: Runtime Error

Solution code:
import collections

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

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)
    
check = [0] * (n+1)
count = [0] * (n+1)

for i in range(q):
    p,x = map(int,input().split())
    count[p] += x
    
def dfs(x):
    check[x] = 1
    for u in g[x]:
        if check[u] == 1:
            continue
        count[u] += count[x]
        dfs(u)
    
dfs(1)

print(*count[1:])

Submission status: Runtime Error

Solution code:
import numpy as np
N,Q = map(int,input().split())
counter = [0]*N
E =[tuple(map(int,input().split())) for _ in range(N-1)]

for i in range(Q):
    p,x = map(int,input().split())
    for e in E:
        if e[0] >= p:
            counter[e[1]-1] += x #list(map(lambda p:p[1]-1, list(filter(lambda e:e[0]>=p,E))))
    counter[p-1] += x
    # print(mask)
    # print(counter)
print("%d "*N % tuple(counter))

Submission status: Runtime Error

Solution code:
import math
import sys
import numpy as np
from collections import defaultdict, deque, Counter 
from itertools import accumulate, product, permutations,combinations, combinations_with_replacement
from operator import itemgetter
from bisect import bisect_left,bisect
from heapq import heappop,heappush
from fractions import gcd

max_value = 1000000000
min_value = -1000000000
sys.setrecursionlimit(max_value)


n,q = map(int,input().split())
edges = []
for i in range(n-1):
	edges.append(list(map(int,input().split())))
for i in range(len(edges)):
	edges[i][0] -= 1
	edges[i][1] -= 1

operations = []
for i in range(q):
	operations.append(list(map(int,input().split())))
for i,e in enumerate(operations):
	operations[i][0] -= 1


parents = [[] for i in range(n)]

for edge in edges:
	parents[edge[1]].append(edge[0])


values = [0 for i in range(n)]

for operation in operations:
	values[operation[0]] += operation[1]


for i in range(1,n):
	values[i] +=  values[parents[i][0]]

print(values)

Submission status: Runtime Error

Solution code:
def count(n, v):
    cnt[n] += v
    for i in nds[n]:count(i, v)

N, Q = map(int, input().split())
cnt = [0 for _ in range(N+1)]
nds = [[] for _ in range(N+1)]
for i in range(N-1):
    a, b = map(int, input().split())
    nds[a].append(b)
for i in range(Q):
    n, v = map(int, input().split())
    count(n, v)
print(' '.join(map(str, cnt[1::])))

Submission status: Runtime Error

Solution code:
def f(p, x, r, tree):
  r[p-1] += x
  children = tree[p]
  for child in children:
    r = f(child, x, r, tree)
  
  return r

N, Q = list(map(int, input().split()))
keys = [i for i in range(1, N+1)]
values = [[] for i in range(N)]
tree = dict(zip(keys, values))

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

r = [0 for i in range(N)]    
for i in range(Q):
  p, x = list(map(int, input().split()))
  r = f(p, x, r, tree)

out = str(r[0])
for i in range(1, N):
  out += ' {0}'.format(r[i])

print(out)

Submission status: Runtime Error

Solution code:
class Node:
    def __init__(self):
        self.data = 0
        self.children = []

    def count(self, v):
        self.data += v
        for n in self.children:
            n.count(v)

N, Q = map(int, input().split())
nodes = [Node() for i in range(N)]
for i in range(N-1):
    a, b = map(int, input().split())
    nodes[a-1].children.append(nodes[b-1])
for i in range(Q):
    n, v = map(int, input().split())
    nodes[n-1].count(v)
print(' '.join(map(lambda x: str(x.data), nodes)))

Submission status: Runtime Error

Solution code:
n, q = tuple([int(i) for i in input().split(' ')])

g = [[] for _ in range(n + 1)]
c = [0 for _ in range(n + 1)]

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

def solve(i, p):
    c[i] += c[p]
    for e in g[i]:
        if e == p:
            continue
        else:
            solve(e, i)

for i in range(q):
    p, x = tuple([int(i) for i in input().split(' ')])
    c[p] += x

import sys
sys.setrecursionlimit(n)

solve(1, 0)

print(' '.join([str(i) for i in c[1:]]))

Submission status: Runtime Error

Solution code:
n, q = tuple([int(i) for i in input().split(' ')])

g = [[] for _ in range(n + 1)]
c = [0 for _ in range(n + 1)]

for i in range(1, n):
    a, b = tuple([int(i) for i in input().split(' ')])
    # かならずしもbはaの子ではないので修正
    g[a].append(b)
    g[b].append(a)

def solve(i, p):
    c[i] += c[p]
    for e in g[i]:
        if e == p:
            continue
        else:
            solve(e, i)

for i in range(q):
    p, x = tuple([int(i) for i in input().split(' ')])
    c[p] += x

solve(1, 0)

print(' '.join([str(i) for i in c[1:]]))

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
from functools import reduce
from operator import itemgetter

N, Q = map(int,input().split())
tree_list = [list(map(int, input().split())) for i in range(N-1)]
counter = [0] * N

for i in range(Q):
    node ,inc = input().split()
    node = int(node)
    counter[node-1] += int(inc)

#sort
tree_list.sort(key=itemgetter(0))
for pa, ch in tree_list:
    counter[ch-1] += counter[pa-1]

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

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
from functools import reduce
from operator import itemgetter

N, Q = map(int,input().split())
tree_list = [list(map(int, input().split())) for i in range(N-1)]
counter = [0] * N

for i in range(Q):
    node ,inc = input().split()
    node = int(node)
    counter[node-1] = int(inc)

#sort
tree_list.sort(key=itemgetter(0))
for pa, ch in tree_list:
    counter[ch-1] += counter[pa-1]

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

Submission status: Runtime Error

Solution code:
n,q = map(int, input().split())
tree = [set() for i in range(n+1)]
for _ in range(n-1):
  a,b = map(int, input().split())
  tree[a].add(b)
  tree[b].add(a)
lazy = [0]*(n+1)
ans = [0]*(n+1)
cnt = 0

for _ in range(q):
  x,v = map(int, input().split())
  lazy[x] += v

def dfs(v,p,tree):
  ans[v] += lazy[v]
  for x in tree[v]:
    if x == p:
      continue
    lazy[x] += lazy[v]
    dfs(x,v,tree)
  lazy[v] = 0
  return

dfs(1,0,tree)

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

Submission status: Runtime Error

Solution code:
def dfs(x, d, s):
    for y in V[x]:
        if d[y]:
            s += f[y]
            cnt[y] = s
            d[y] = 0
            dfs(y, d, s)
            s -= f[y]


N, Q = map(int, input().split())  # N頂点, Q個の操作
V = [[] for i in range(N)]  # グラフの情報を格納する
for i in range(N-1):  # 辺の個数はN-1個
    a, b = map(lambda x: int(x)-1, input().split())
    V[a].append(b)
    V[b].append(a)

f = [0]*N

for i in range(Q):  # Q個の操作についての情報
    p, x = map(int, input().split())
    p -= 1
    f[p] += x  # 頂点pをルートにもつ部分技にはxが足されていく

cnt = [0]*N  # 各頂点のカウンター

d = [1]*N
d[0] = 0

cnt[0] = f[0]  # ルートに足される値は確定している

s = f[0]
dfs(0, d, s)
print(" ".join(map(str, cnt)))

Submission status: Runtime Error

Solution code:
def D():
    def dfs(x,d,s):
        for y in v[x]:
            if d[y]:
                s += f[y]
                ans[y] = s
                d[y] = 0
                dfs(y,d,s)
                s -= f[y]
    n,q = LI()
    v = [[] for i in range(n)]
    for i in range(n-1):
        a,b = LI()
        a -= 1
        b -= 1
        v[a].append(b)
        v[b].append(a)
    f = [0]*n
    for i in range(q):
        p,x = LI()
        p -= 1
        f[p] += x
    ans = [0]*n
    d = [1]*n
    d[0] = 0
    ans[0] = f[0]
    s = f[0]
    dfs(0,d,s)
    print(*ans)
    return
 
#Solve
if __name__ == "__main__":
    D()

Submission status: Runtime Error

Solution code:
import numpy as np
N,Q = map(int,input().split())
arr_2d = np.zeros((N,N),dtype=bool)
counter = np.zeros(N,dtype=int)

Submission status: Runtime Error

Solution code:
import numpy as np
N,Q = map(int,input().split())
arr_2d = np.zeros((N,N),dtype=bool)
counter = np.zeros(N,dtype=int)
for _ in range(N-1):
    i,j = map(int,input().split())
    arr_2d[i-1][j-1] = True

for i in range(Q):
    p,x = map(int,input().split())
    mask_ = list(filter(lambda xy:(xy[0] >= p-1 and xy[1] >= p-1), np.argwhere(arr_2d)))
    mask = list(map(lambda xy:xy[1],mask_)) if len(mask_) else []
    mask.append(p-1)
    counter[mask] += x

print("%d "*N % tuple(counter))

Submission status: Runtime Error

Solution code:
import numpy as np
N,Q = map(int,input().split())
arr_2d = np.zeros((N,N),dtype=bool)
counter = np.zeros(N,dtype=int)
for i in range(N-1):
    i,j = map(int,input().split())
    arr_2d[i-1][j-1] = True

Submission status: Runtime Error

Solution code:
import numpy as np
N,Q = map(int,input().split())
arr_2d = np.zeros((N,N),dtype=bool)
counter = np.zeros(N,dtype=int)
for i in range(N-1):
    i,j = map(int,input().split())
    arr_2d[i-1][j-1] = True

for i in range(Q):
    p,x = map(int,input().split())
    mask_ = list(filter(lambda xy:(xy[0] >= p-1 and xy[1] >= p-1), np.argwhere(arr_2d)))
    mask = list(map(lambda xy:xy[1],mask_)) if len(mask_) else []
    mask.append(p-1)
    counter[mask] += x

print("%d "*N % tuple(counter))

Submission status: Runtime Error

Solution code:
import numpy as np
N,Q = map(int,input().split())
arr_2d = np.zeros((N,N),dtype=bool)
counter = np.zeros(N,dtype=int)
for i in range(N-1):
    i,j = map(int,input().split())
    arr_2d[i-1][j-1] = True

for i in range(Q):
    p,x = map(int,input().split())
    mask_ = list(filter(lambda xy:(xy[0] >= p-1 and xy[1] >= p-1), np.argwhere(arr_2d)))
    if len(mask_):
        mask = list(map(lambda xy:xy[1],mask_))
    mask.append(p-1)
    counter[mask] += x

print("%d "*N % tuple(counter))

Submission status: Runtime Error

Solution code:
import numpy as np
N,Q = map(int,input().split())
arr_2d = np.zeros((N,N),dtype=bool)
counter = np.zeros(N,dtype=int)
for i in range(N-1):
    i,j = map(int,input().split())
    arr_2d[i-1][j-1] = True

for i in range(Q):
    p,x = map(int,input().split())
    mask_ = list(filter(lambda xy:(xy[0] >= p-1 and xy[1] >= p-1), np.argwhere(arr_2d)))
    if not len(mask_):
        continue    
    mask = list(map(lambda xy:xy[1],mask_))
    mask.append(p-1)
    counter[mask] += x

print("%d "*N % tuple(counter))

Submission status: Runtime Error

Solution code:
import numpy as np
N,Q = map(int,input().split())
arr_2d = np.zeros((N,N),dtype=bool)
counter = np.zeros(N,dtype=int)
for i in range(N-1):
    i,j = map(int,input().split())
    arr_2d[i-1][j-1] = True

for i in range(Q):
    p,x = map(int,input().split())
    mask = list(map(lambda xy:xy[1],filter(lambda xy:(xy[0] >= p-1 and xy[1] >= p-1), np.argwhere(arr_2d))))
    mask.append(p-1)
    counter[mask] += x

print("%d "*N % tuple(counter))

Submission status: Runtime Error

Solution code:
def child_search(add_set, ki_dict, Ne):
    add_set.add(Ne)
    child_list = ki_dict[Ne]

    for child in child_list:
        add_set = child_search(add_set, ki_dict, child)

    return add_set

def main():
    N, Q = [int(i) for i in input().split(' ')]
    ki_list = []
    val_dict = {}

    for i in range(N):
        val_dict[i] = 0
        ki_list.append([])

    for i in range(N-1):
        Ne, Ha = [int(i) for i in input().split(' ')]
        ki_list[Ne-1].append(Ha-1)

    for i in range(Q):
        Ne, value = [int(j) for j in input().split(' ')]
        add_set = set()

        add_set = child_search(add_set, ki_list, Ne - 1)

        for sum_ind in add_set:
            val_dict[sum_ind] += value

    result_list = [str(i) for i in val_dict.values()]

    print(' '.join(result_list))

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
def child_search(add_set, ki_dict, Ne):
    add_set.add(Ne)
    child_list = ki_dict[Ne]

    for child in child_list:
        add_set.add(child)
        add_set = child_search(add_set, ki_dict, child)

    return add_set

def main():
    N, Q = [int(i) for i in input().split(' ')]
    ki_dict = {}
    val_dict = {}

    for i in range(N):
        val_dict[i] = 0
        ki_dict[i] = []

    for i in range(N-1):
        Ne, Ha = [int(i) for i in input().split(' ')]
        ki_dict[Ne - 1].append(Ha - 1)

    for i in range(Q):
        Ne, value = [int(j) for j in input().split(' ')]
        add_set = set()

        add_set = child_search(add_set, ki_dict, Ne - 1)

        for sum_ind in add_set:
            val_dict[sum_ind] += value

    result_list = [str(i) for i in val_dict.values()]

    print(' '.join(result_list))

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
def child_search(add_set, ki_dict, Ne):
    add_set.add(Ne)
    child_list = ki_dict[Ne]

    if(len(child_list) != 0):
        for child in child_list:
            child_search(add_set, ki_dict, child)

    return add_set

def main():
    N, Q = [int(i) for i in input().split(' ')]
    ki_dict = {}
    val_dict = {}

    for i in range(N):
        val_dict[i] = 0
        ki_dict[i] = []

    for i in range(N-1):
        Ne, Ha = [int(i) for i in input().split(' ')]
        ki_dict[Ne - 1].append(Ha - 1)

    for i in range(Q):
        Ne, value = [int(j) for j in input().split(' ')]
        add_set = set()

        add_set = child_search(add_set, ki_dict, Ne - 1)

        for sum_ind in add_set:
            val_dict[sum_ind] += value

    result_list = [str(i) for i in val_dict.values()]

    print(' '.join(result_list))

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
def child_search(add_set, ki_dict, Ne):
    add_set.add(Ne)
    child_list = ki_dict[Ne]

    if(len(child_list) != 0):
        for child in child_list:
            child_search(add_set, ki_dict, child)

    return add_set

def main():
    N, Q = [int(i) for i in input().split(' ')]
    ki_dict = {}
    val_dict = {}

    for i in range(N):
        val_dict[i] = 0
        ki_dict[i] = []

    for i in range(N-1):
        Ne, Ha = [int(i) for i in input().split(' ')]
        ki_dict[Ne - 1].append(Ha - 1)

    print(ki_dict)

    for i in range(Q):
        Ne, value = [int(j) for j in input().split(' ')]
        add_set = set()

        add_set = child_search(add_set, ki_dict, Ne - 1)
        print(add_set)

        for sum_ind in add_set:
            val_dict[sum_ind] += value

    result_list = [str(i) for i in val_dict.values()]

    print(' '.join(result_list))

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
n, q = map(int, input().split())
to = [[] for i in range(n)]
ans = [0 for i in range(n)]
def dfs(v, p = -1):
    for u in to[v]:
        if u == p:
            continue
        ans[u] += ans[v]
        dfs(u, v)
for i in range(n - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    to[a].append(b)
    to[b].append(a)
for i in range(q):
    p, x = map(int, input().split())
    p -= 1
    ans[p] += x
dfs(0)
print(" ".join(map(str, ans)))

Submission status: Runtime Error

Solution code:
class Node:
    def __init__(self, index, parent_index):
        self.index = index
        self.parent_index = parent_index
        self.children = []
        self.value = 0

    def add_value(self, value):
        if self.index > 0:
            self.value += value
            for child in self.children:
                child.add_value(value)


class Tree:
    def __init__(self):
        self.node_indices = {}
        self.nodes = []

        self.add_node(1, 0)

    def add_node(self, index, parent_index):
        node = Node(index, parent_index)
        self.node_indices[index] = len(self.nodes)
        self.nodes.append(node)

        if index > 1:
            parent_node = self.nodes[self.node_indices[parent_index]]
            parent_node.children.append(node)

    def add_value(self, index, value):
        node = self.nodes[self.node_indices[index]]
        node.add_value(value)


def main():
    n, q = map(int, input().split())

    tree = Tree()
    for _ in range(n - 1):
        parent_index, child_index = map(int, input().split())
        tree.add_node(child_index, parent_index)

    for _ in range(q):
        index, value = map(int, input().split())
        tree.add_value(index, value)

    res = []
    for index in range(1, n + 1):
        node = tree.nodes[tree.node_indices[index]]
        res.append(node.value)
    print(' '.join(map(str, res)))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
class Node:
    def __init__(self, index, parent_index):
        self.index = index
        self.parent_index = parent_index
        self.children = []
        self.value = 0

    def add_value(self, value):
        if self.index > 0:
            self.value += value
            for child in self.children:
                child.add_value(value)


class Tree:
    def __init__(self):
        self.node_indices = {}
        self.nodes = []

        self.add_node(1, 0)

    def add_node(self, index, parent_index):
        node = Node(index, parent_index)
        self.node_indices[index] = len(self.nodes)
        self.nodes.append(node)

        if index > 1:
            parent_node = self.nodes[self.node_indices[parent_index]]
            parent_node.children.append(node)

    def add_value(self, index, value):
        node = self.nodes[self.node_indices[index]]
        node.add_value(value)


def main():
    n, q = map(int, input().split())

    tree = Tree()
    for _ in range(n - 1):
        parent_index, child_index = map(int, input().split())
        tree.add_node(child_index, parent_index)

    for _ in range(q):
        index, value = map(int, input().split())
        print(index, value)
        tree.add_value(index, value)

    res = []
    for index in range(1, n + 1):
        node = tree.nodes[tree.node_indices[index]]
        res.append(node.value)
    print(' '.join(map(str, res)))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n, q = map(int, input().split())
# [[child, ], ]
tree = [[] for _ in range(n)]
for _ in range(n-1):
  a, b = map(int, input().split())
  tree[min(a, b)-1].append(max(a, b))

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

def pass_cnt(p):
  for child in tree[p-1]:
    cnt[child-1] += cnt[p-1]
    pass_cnt(child)

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

Submission status: Runtime Error

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

edges = {}

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

stack = [1]
while len(stack) > 0:
  node = stack.pop()
  for child in edges[node]:
    edges[child].remove(node)
    stack.append(child)
    
counters = [0] * (n + 1)

def count(node, x):
  counters[node] += x
  for child in edges[node]:
    count(child, x)

for i in range(q):
  p, x = map(int, input().split())
  count(p, x)
  
print(' '.join(list(map(str, counters[1:]))))

Submission status: Runtime Error

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

edges = {}

for i in range(n):
  a, b = map(int, input().split())
  if edges.haskey(a):
    edges[a].append(b)
  else:
    edges[a] = [b]
    
  if edges.haskey(b):
    edges[b].append(a)
  else:
    edges[b] = [a]

stack = [1]
while len(stack) > 0:
  node = stack.pop()
  for child in edges[node]:
    edges[child].remove(node)
    stack.append(child)
    
counters = [0] * (n + 1)

def count(node, x):
  counter[node] += x
  for child in edges[node]:
    count(child, x)

for i in range(q):
  p, x = map(int, input().split())
  count(p, x)
  
print(' '.join(list(map(int, counters[1:]))))

Submission status: Runtime Error

Solution code:
def dfs(tree, count, p):
    for i in tree[p]:
        count[i] += count[p]
        dfs(tree, count, i)


def main():
    N, Q = map(int, input().split())
    tree = {i+1: [] for i in range(N)}
    count = {i+1: 0 for i in range(N)}

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

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

    dfs(tree, count, 1)

    ans = [str(count[k]) for k in sorted(count.keys())]
    print(" ".join(ans))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
def dfs(tree, count, p):
    for i in tree[p]:
        count[i] += count[p]
        dfs(tree, count, i)


def find_root(inv):
    return [k for k in inv if len(inv[k]) == 0][0]


def main():
    N, Q = map(int, input().split())
    tree = {i+1: [] for i in range(N)}
    inv = {i+1: [] for i in range(N)}
    count = {i+1: 0 for i in range(N)}

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

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

    dfs(tree, count, find_root(inv))

    print(" ".join(map(str, sorted(count.values()))))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
def dfs(tree, count, p):
    for i in tree[p]:
        count[i] += count[p]
        dfs(tree, count, i)


def find_root(inv):
    return [k for k in inv if len(inv[k]) == 0][0]


def main():
    N, Q = map(int, input().split())
    tree = {i+1: [] for i in range(N)}
    inv = {i+1: [] for i in range(N)}
    count = {i+1: 0 for i in range(N)}

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

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

    dfs(tree, count, find_root(inv))

    print(" ".join(map(str, count.values())))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
def dfs(tree, count, p, x):
    count[p] += x
    for i in tree[p]:
        dfs(tree, count, i, x)


def main():
    N, Q = map(int, input().split())
    tree = {i+1: [] for i in range(N)}
    count = {i+1: 0 for i in range(N)}

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

    for _ in range(Q):
        p, x = map(int, input().split())
        dfs(tree, count, p, x)

    print(" ".join(map(str, count.values())))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
class Node:

    def __init__(self, p):
        self.index = p
        self.count = 0

    def __repr__(self):
        return f"{self.index}({self.count})"


def dfs(tree, count, p, x):
    count[p] += x
    for node in tree[p]:
        dfs(tree, count, node.index, x)


def main():
    N, Q = map(int, input().split())
    tree = {i+1: [] for i in range(N)}
    count = {i+1: 0 for i in range(N)}

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

    for _ in range(Q):
        p, x = map(int, input().split())
        dfs(tree, count, p, x)

    # pprint.pprint(count)
    print(" ".join(map(str, count.values())))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
from collections import namedtuple, defaultdict
import pprint


class Node:

    def __init__(self, p):
        self.index = p
        self.count = 0

    def __repr__(self):
        return f"{self.index}({self.count})"


def dfs(tree, count, p, x):
    # print("dfs", p, x)
    count[p] += x
    for node in tree[p]:
        dfs(tree, count, node.index, x)


def main():
    N, Q = map(int, input().split())
    tree = defaultdict(list)
    count = {i+1: 0 for i in range(N)}

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

    for _ in range(Q):
        p, x = map(int, input().split())
        dfs(tree, count, p, x)

    # pprint.pprint(count)
    print(" ".join(map(str, count.values())))


if __name__ == '__main__':
    main()