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 defaultdict
import sys
import math
from datetime import datetime


class TreeNode:
    def __init__(self):
        self.val = 0
        self.vertex = []

def make_trees(n, A, B):
    trees = []
    for i in range(n):
        trees.append(TreeNode())
    for i in range(len(A)):
        a = A[i]-1
        b = B[i]-1
        trees[a].vertex.append(b)
    return trees

def dfs(node: TreeNode, x: int, trees):
    if node:
        node.val += x
        for i in node.vertex:
            dfs(trees[i], x, trees)


def sol(n, q, A, B, P, X):
    trees = make_trees(n, A, B)
    for i in range(len(P)):
        p = P[i]-1
        x = X[i]
        t = trees[p]
        # dfs, give point x
        dfs(t, x, trees)
    #
    return " ".join([str(t.val)  for t in trees])
    #return n, q, A, B, P, X



do_submit = True
#do_submit = False

def input_parse(input_str):
    lines = [x.strip() for x in input_str.split("\n") if x.strip()]
    parsed_lines = [list(map(str, line.split())) for line in lines]
    print(parsed_lines)
    n = int(parsed_lines[0][0])
    q = int(parsed_lines[0][1])
    A = []
    B = []
    P = []
    X = []
    for i in range(1, n-1+1):
        a = int(parsed_lines[i][0])
        b = int(parsed_lines[i][1])
        A.append(a)
        B.append(b)
    for i in range(n, 1+n+q-1):
        p = int(parsed_lines[i][0])
        x = int(parsed_lines[i][1])
        P.append(p)
        X.append(x)

    # S = parsed_lines[1][0]
    # return n, k, S
    return n, q, A, B, P, X


if not do_submit:
    n, q, A, B, P, X = input_parse("""
    4 3
    1 2
    2 3
    2 4
    2 10
    1 100
    3 1
    """)
    print(sol(n, q, A, B, P, X))

    n, q, A, B, P, X = input_parse("""
        6 2
        1 2
        1 3
        2 4
        3 6
        2 5
        1 10
        1 10
    """)
    print(sol(n, q, A, B, P, X))

else:
    # n = int(input().strip())
    # q = int(input().strip())
    n, q = list(map(int, input().split()))
    A = []
    B = []
    P = []
    X = []
    for i in range(n-1):
        a, b = list(map(int, input().split()))
        # a = int(input().strip())
        # b = int(input().strip())
        A.append(a)
        B.append(b)
    for i in range(q):
        p, x = list(map(int, input().split()))
        # p = int(input().strip())
        # x = int(input().strip())
        P.append(p)
        X.append(x)
    print(sol(n, q, A, B, P, X))

Submission status: Runtime Error

Solution code:
from collections import defaultdict
import math
if __name__ == '__main__':
    n,q = (int(i) for i in input().split())
    parent = [0 for i in range(math.floor(2e+5))]
    for i in range(n-1):
        num1,num2 = (int(k) for k in input().split())
        parent[num2] = num1
    
    counter = defaultdict(list)
    for i in range(q):
        num1,num2 = (int(k) for k in input().split())
        counter[num1].append(num2)

    dp = [0,sum(counter[1])]
    for i in range(1,n+1):
        ans=0
        if(i==1):
            print(sum(counter[i]),end=" ")
        else:
            ans = dp[parent[i]]+sum(counter[i])
            print(ans,end=" ")
            dp.append(ans)

Submission status: Runtime Error

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

res = [0]*(n+1)
def add_x(p, x):
    res[p] += x
    for child in tree[p]:
        new_x = x+adds[child]
        add_x(child, new_x)

add_x(1, adds[1])

print(' '.join(list(map(str, res[1:]))))

Submission status: Runtime Error

Solution code:
# 2019/08/18
# AtCoder Beginner Contest 138 - D

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

pdict = dict()
sdict = dict()

#for i in range(1, n+1):
#    sdict[i] = list()
#    sdict[i].append(i)

# Make Tree
for i in range(n-1):
    # Init
    sdict[i+1] = list()
    sdict[i+1].append(i+1)

    # Input
    a, b = map(int,input().split())
    pdict[b] = a
#    if sdict.get(a) == None:
#        sdict[a] = list()
#        sdict[a].append(a)
    sdict[a].append(b)
    
    wka = a
    while(wka != 1):
        sdict[pdict[wka]].append(b)
        wka = pdict[wka]

anslist = [0] * (n + 1)

# Calc
for i in range(q):
    # Input
    p, x = map(int,input().split())
#    anslist[p] = anslist[p] + x
    for j in range(len(sdict[p])):
        anslist[sdict[p][j]] = anslist[sdict[p][j]] + x

# Output
anslist.remove(0)
print(*anslist)

Submission status: Runtime Error

Solution code:
def func(now, ans_base, num, tree):
    ans_base.append(num[now])
    addNum = num[now]
    while len(tree[now]) > 0:
        next = tree[now].pop(0)
        num[next] += num[now]
        ans_base = func(next, ans_base, num, tree)
    return ans_base


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

tree = {}
for i in range(1, N + 1):
    tree[i] = list()

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

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

ans_base = list()

result = func(1, ans_base, num, tree)

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

Submission status: Runtime Error

Solution code:
def repeat(index, cost):
    if index in dict_tree:
        for k in dict_tree[index]:
            if k in cost:
                break
            else:
                cost.append(k)
                point[k-1] += x
                repeat(k, cost)
            
    else:
        return

n, q = map(int, input().split())
dict_tree = {}
for i in range(n-1):
    a, b = map(int, input().split())
    if a in dict_tree:
        dict_tree[a].append(b)
    else:
        dict_tree[a] = [b]
point = [0] * n

for j in range(q):
    p, x = map(int, input().split())
    cost = []
    cost.append(p)
    repeat(p, cost)

for m in point:
    print(m)

Submission status: Runtime Error

Solution code:
import numpy as np

n, q = map(int, input().split())
edges=[[] for i in range(n+1)]
d_from_1=[-1 for i in range(n+1)]
ans = [0 for i in range(n+1)]

for i in range(1,n):
	a, b=[int(i) for i in input().split()]
	edges[a].append([b,1])
	edges[b].append([a,1])
def kyori_from_1(u):
	for v,w in edges[u]:
		if d_from_1[v]==-1:
			d_from_1[v]=d_from_1[u]+w
			kyori_from_1(v)

d_from_1[1]=0
kyori_from_1(1)

px = []
for i in range(q):
    p, x = map(int, input().split())
    px.append([p, x])


d_from_p = [-1 for i in range(n+1)]
def kyori_from_p(u):
	for v,w in edges[u]:
		if d_from_p[v]==-1:
			d_from_p[v]=d_from_p[u]+w
			kyori_from_p(v)

for i in range(q):
    d_from_p = [-1 for i in range(n+1)]
    d_from_p[px[i][0]] = 0
    kyori_from_p(px[i][0])
    for j in range(1, n+1):
        if px[i][0] == 1:
            ans[j] += px[i][1]
        elif d_from_1[j] >= d_from_1[px[i][0]] and d_from_p[j] < d_from_1[j]:
            ans[j] += px[i][1]

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

Submission status: Runtime Error

Solution code:
from collections import defaultdict


class Node:
    def __init__(self):
        self.num = 0
        self.node_list = []

    def add(self, add_num):
        self.num += add_num
        for node in self.node_list:
            node.add(add_num)

setting_str = input()
setting_str_list = setting_str.split(" ")
N = int(setting_str_list[0])
Q = int(setting_str_list[1])
node_dict = {}
for i in range(1, N+1):
    node_dict[i] = Node()

for i in range(N-1):
    num_str  = input()
    num_str_list = num_str.split(" ")
    a = int(num_str_list[0])
    b = int(num_str_list[1])
    node_dict[a].node_list.append(node_dict[b])

add_dict = defaultdict(int)
for i in range(Q):
    num_str = input()
    num_str_list = num_str.split(" ")
    a = int(num_str_list[0])
    b = int(num_str_list[1])
    add_dict[a] += b

for k, v in add_dict.items():
    node_dict[k].add(v)

result = ""
for node in node_dict.values():
    result += str(node.num) + " "
result = result[:-1]
print(result)

Submission status: Runtime Error

Solution code:
class Node:
    def __init__(self, key):
        self.key = key
        self.child = []
        self.point = 0

n, q = map(int, input().split())
a, b, p, x = [], [], [], []
nodes = []
nodes.append(None)
ans = []

for i in range(n-1):
    temp1, temp2 = map(int, input().split())
    a.append(temp1)
    b.append(temp2)

for i in range(q):
    temp1, temp2 = map(int, input().split())
    p.append(temp1)
    x.append(temp2)

# Make node list
for i in range(1, n+1):
    node = Node(i)
    nodes.append(node)


for i in range(n-1):
    nodeParent = nodes[a[i]]
    nodeChild = nodes[b[i]]
    nodeParent.child.append(nodeChild)

def printNode(node):
#    print(node.point)
    ans.append(node.point)
    for child in node.child:
        printNode(child)

def addCount(node, point):
    node.point += point
    # for child in node.child:
    #     addCount(child, point)

def traverse(node, point):
#    print(node.point)
    node.point += point
    for child in node.child:
        traverse(child, node.point)

for i in range(q):
    node = nodes[p[i]]
    addCount(node, x[i])

traverse(nodes[1], 0)
printNode(nodes[1])

print(' '.join([str(i) for i in ans]))

Submission status: Runtime Error

Solution code:

N,Q = [int(i) for i in input().split()]


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

for i in range(1,Q+1):
    p1,x1=[int(i) for i in input().split()]
    p.append(p1)
    x.append(x1)
    
sum_N = []
for i in range(1,Q + 1):
  for k in range(1,N):
    if p[i] == a[k]:
      sum_N[a[k]] = sum_N[a[k]] + x[i]
      sum_N[b[k]] = sum_N[b[k]] + x[i]
      if a[s] == b[k] and k<s:
        sum_N[a[s]] = sum_N[a[s]] + x[i]
        sum_N[b[s]] = sum_N[b[s]] + x[i]
        if a[w] == b[s] and s<w:
          sum_N[a[w]] = sum_N[a[w]] + x[i]
          sum_N[b[s]] = sum_N[b[s]] + x[i]

print(sum_N)

Submission status: Runtime Error

Solution code:
tmp = list(map(int, input().split()))
N, Q = tmp[0], tmp[1]

import numpy as np

tree = np.zeros([N,N])
for i in range(N-1):
    tmp = list(map(int, input().split()))
    tree[tmp[0]-1,tmp[1]-1] = 1

point = np.zeros([N])
for i in range(Q):
    q = list(map(int, input().split()))
    q_tmp = np.where(tree[(q[0]-1):,:] == 1)
    #print(q_tmp[1])
    #print(q_tmp[1].shape)
    if str(q_tmp[1].shape) == '(0,)':
        #print('nan')
        point[q[0]-1] += int(q[1])
    else:
        for j in q_tmp[1]:
            point[j] += int(q[1])
        point[q[0]-1] += int(q[1])

point = point.tolist()
point= [int(n) for n in point]

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

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
tree = [list(map(int, input().split())) for i in range(N-1)]
process =  [list(map(int, input().split())) for i in range(Q)]

def next_node(node_num):
    next_nodes = []
    for edge in tree:
        if edge[0] == node_num:
            next_nodes.append(edge[1])
    return next_nodes

def all_nodes(num):
  x = [] 
  add_nodes = next_node(num)
  while add_nodes != []:
    for i in add_nodes:
      add_nodes += next_node(i) 
      x += add_nodes
        add_nodes = []
  return x


def add(score, procedure):
  "procedure = [p, x]"
  score[procedure[0]-1] += procedure[1]
  for n in all_nodes(procedure[0]):
    print(n)
    score[n-1] += procedure[1]
  return score


score = [0]*N
for procedure in process:
    add(score, procedure)
print(score)

Submission status: Runtime Error

Solution code:
import sys

def add_count(addnum, relations, counters, nodelist):
  new_nodelist = []
  for node in nodelist:
    if node not in relations:
      continue
    else:
      new_nodelist = new_nodelist + relations[node]
      for child in relations[node]:
        counters[child-1] += addnum
  
  if len(new_nodelist) == 0:
    return counters
  else:
    return add_count(addnum, relations, counters, new_nodelist)

N, Q = map(int, sys.stdin.readline().split())
alist = list(list(map(int, sys.stdin.readline().split())) for i in range(N-1))
qlist = list(list(map(int, sys.stdin.readline().split())) for i in range(Q))

counters = [0 for i in range(N)]
relations = {}
for a in alist:
  if a[0] not in relations:
    relations[a[0]] = [a[1]]
  else:
    relations[a[0]].append(a[1])

for q in qlist:
  counters[q[0]-1] += q[1]
  if q[0] in relations:
    counters = add_count(q[1], relations, counters, [q[0]])

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

Submission status: Runtime Error

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

class Node:
    def __init__(self, root):
        self.root = root
        self.children = []
        self.val = 0

    def add_child(self, child_node):
        self.children.append(child_node)
        if self.root is not None:
            self.root.add_child(child_node)

nodes = [None] * n
nodes[0] = Node(None)

for i in range(1, n):
    a, b = map(int, input().split())
    a_node = nodes[a - 1]
    if nodes[b - 1] is None:
        b_node = Node(a_node)
        nodes[b - 1] = b_node
    a_node.add_child(nodes[b - 1])

for j in range(q):
    p, x = map(int, input().split())
    node = nodes[p - 1]
    if node is None:
        continue
    node.val += x
    children = node.children
    for child in children:
        child.val += x

res = []
for node in nodes:
    res.append(str(node.val))
print(" ".join(res))

Submission status: Runtime Error

Solution code:
N,Q=map(int,input().split())
dg={i:[] for i in range(1,N+1)}
for i in range(1,N):
    a,b=map(int,input().split())
    dg[a].append(b)
    dg[b].append(a)
#print(dg)
def habatan(p,me):
    if me!=1:
        dg[me].remove(p)
    for c in dg[me]:
        habatan(me,c)

habatan(0,1)#dg親消し
#print(dg)
dv={i:0 for i in range(1,N+1)}
for i in range(Q):
    p,x=map(int,input().split())
    dv[p]+=x
#dans={}
def habatan1(p,me):
    if me!=1:
        dv[me]+=dv[p]
    for c in dg[me]:
        habatan1(me,c)
habatan1(0,1)
for i in range(1,N+1):
    print(dv[i],end=" ")
print("")

Submission status: Runtime Error

Solution code:
from collections import defaultdict
import sys
import math
from datetime import datetime
from typing import List


class TreeNode:
    def __init__(self):
        self.val = 0
        self.vertex = []

def make_trees(n, A, B):
    trees = []
    for i in range(n):
        trees.append(TreeNode())
    for i in range(len(A)):
        a = A[i]-1
        b = B[i]-1
        trees[a].vertex.append(b)
    return trees

def dfs(node: TreeNode, x: int, trees):
    if node:
        node.val += x
        for i in node.vertex:
            dfs(trees[i], x, trees)


def sol(n, q, A, B, P, X):
    trees = make_trees(n, A, B)
    for i in range(len(P)):
        p = P[i]-1
        x = X[i]
        t = trees[p]
        # dfs, give point x
        dfs(t, x, trees)
    #
    return " ".join([str(t.val)  for t in trees])
    #return n, q, A, B, P, X



do_submit = True
#do_submit = False

def input_parse(input_str):
    lines = [x.strip() for x in input_str.split("\n") if x.strip()]
    parsed_lines = [list(map(str, line.split())) for line in lines]
    print(parsed_lines)
    n = int(parsed_lines[0][0])
    q = int(parsed_lines[0][1])
    A = []
    B = []
    P = []
    X = []
    for i in range(1, n-1+1):
        a = int(parsed_lines[i][0])
        b = int(parsed_lines[i][1])
        A.append(a)
        B.append(b)
    for i in range(n, 1+n+q-1):
        p = int(parsed_lines[i][0])
        x = int(parsed_lines[i][1])
        P.append(p)
        X.append(x)

    # S = parsed_lines[1][0]
    # return n, k, S
    return n, q, A, B, P, X


if not do_submit:
    n, q, A, B, P, X = input_parse("""
    4 3
    1 2
    2 3
    2 4
    2 10
    1 100
    3 1
    """)
    print(sol(n, q, A, B, P, X))

else:
    # n = int(input().strip())
    # q = int(input().strip())
    n, q = list(map(int, input().split()))
    A = []
    B = []
    P = []
    X = []
    for i in range(n-1):
        a, b = list(map(int, input().split()))
        # a = int(input().strip())
        # b = int(input().strip())
        A.append(a)
        B.append(b)
    for i in range(q):
        p, x = list(map(int, input().split()))
        # p = int(input().strip())
        # x = int(input().strip())
        P.append(p)
        X.append(x)
    print(sol(n, q, A, B, P, X))

Submission status: Runtime Error

Solution code:
import numpy as np
n,q=list(map(int, input().split()))
result = {i+1:0 for i in range(n)}
ar = np.eye(n)

for i in range(n-1):
    a,b = list(map(int, input().split()))
    ar[0:a,a-1:b] += 1
for i in range(q):
    a,b = list(map(int, input().split()))
    m = ar[a-1]
    for j in range(len(m)):
        if m[j] != 0:
            result[j+1] += b
r = list(result.values())
res = map(str, r)
print(' '.join(res))

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(200000)
input = sys.stdin.readline'''
allinputs = iter(input().splitlines())
input = lambda : next(allinputs)
#'''
N, Q = map(int, input().split())
#a = [0] * (N - 1)
#b = [0] * (N - 1)
p = [0] * Q
x = [0] * Q
link = [[] for _ in range(N)]
children = [[i] for i in range(N)]
arrived = [0] * N

def dps(v):
	arrived[v] = 1
	tmp_list = []
	
	for i in link[v]:
		if arrived[i] == 0:
			tmp_list.append(dps(i))
			
	for j in tmp_list:
		for k in j:
			children[v].append(k)
		
	return children[v]

for i in range(N - 1):
	#a[i], b[i] = map(int, input().split())
	a, b = map(int, input().split())
	a -= 1
	b -= 1
	link[a].append(b)
	link[b].append(a)
	
dps(0)
ans = [0] * N
	
for i in range(Q):
	tmp_p, x[i] = map(int, input().split())
	p[i] = tmp_p - 1
	
	for j in children[p[i]]:
		ans[j] += x[i]
		
for i in range(N):
	print(ans[i], end=' ')

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
 
# pt, oya, ko
ki = [[0, 0, []] for i in range(N)]
 
def dfs(target, p, x):
  target.extend(ki[p-1][2])
  ki[p-1][0] += x
  target.pop(0)
  
  if len(target) == 0:
    return
  else:
  	dfs(target, target[0], x)
    
for i in range(N-1):
  a, b = map(int, input().split())
  ki[a-1][2].append(b)
  ki[b-1][1] = a
  
for i in range(Q):
  p, x = map(int, input().split())
  
  target = [p]
  dfs(target, p, x)
  
for i in ki:
  print(str(i[0]), end=" ")

Submission status: Runtime Error

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

T = dict()
V = np.zeros(N+1)

a, b = map(int, input().split())
T[a] = []
T[a].append(b)

for i in range(N-2):
	a, b = map(int, input().split())
	if T.get(a) == None:
		T[a] = []
	T[a].append(b)

def change(a, v):
	V[a] += v
	temp = T.get(a)
	if(temp==None):
		return
	else:
		for x in temp:
			change(x, v)
		

for i in range(Q):
	a, v = map(int, input().split())
	change(a, v)

print(' '.join([str(int(x)) for x in V[1:]]))

Submission status: Runtime Error

Solution code:
def check_child(index, Child, Values, parent, progeny):
    for i in Child[index]:
        for j in parent:
            progeny[j].append(i)
        parent.append(i)
        check_child(i, Child, Values, parent, progeny)
        parent.pop()


def main():
    N, Q = map(int, input().split())
    Child = [[] for _ in range(N+1)]
    progeny = [[] for _ in range(N+1)]
    Values = [0 for _ in range(N+1)]
    parent = [1]
    for _ in range(1, N):
        a, b = map(int, input().split())
        Child[a].append(b)

    check_child(1, Child, Values, parent, progeny)

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

    print(*Values[1:])


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
def get_verteces_in_subtree():
    mem = {}
    
    def func(vertex):
        if vertex in mem.keys():
            return mem[vertex]
        
        children = tree_dictionary[vertex]
        if len(children) == 0:
            answer = [vertex]
        else:
            answer = [vertex] + sum([func(child) for child in children], [])
        mem[vertex] = answer
        return answer
    return func
  
get_verteces_in_subtree = get_verteces_in_subtree()

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

tree_dictionary = {i: [] for i in range(1, N+1)}
for edge in edges:
    tree_dictionary[edge[0]].append(edge[1])

counts = [0] * N
for op in operations:
    top_vertex, value = op
    added_verteces = get_verteces_in_subtree(top_vertex)
    for v in added_verteces:
        counts[v-1] += value

output = ""
for c in counts:
    output += (str(c) + " ")
output = output[:-1]
print(output)

Submission status: Runtime Error

Solution code:
import numpy as np

import sys
sys.setrecursionlimit(10**6)

n, q = map(int, input().split())
g = np.zeros((n+1,n+1))

ans = np.zeros((n)) #Do not Foget -1


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

#for i in range(n+1):
#    print(g[0])

c = []
for i in range(n+1):
    c.append([i])
for j in reversed(range(n+1)):
    for i in range(n+1):
        if g[i][j] == 1:
            c[i]+=c[j]

#print(c)



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


ans_str = str(ans.astype(int))
ans_str = ans_str.replace('[','').replace(']','')
print(ans_str)

Submission status: Runtime Error

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

w = np.zeros((N, N))
c = np.zeros((N, 1))

def plus(w, p, x, c, N):
  cl = c
  cl[p-1]+=x
  for i in range(p - 1, N):
    for j in range(N):
      if(w[i, j]) == 1:
        cl[j] += x
  return cl

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

for j in range(Q):
  p, x = map(int, input().split())
  c = plus(w, p, x, c, N)

out = ""
for i in range(N):
  out += "{}".format(int(c[i,0])) + " "
print(out)

Submission status: Runtime Error

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


class Graph:
    def __init__(self):
        """ ノードのつながりを辞書型で表現する """
        self.adjacency_dict = {}
        # 頂点カウンターを用意しておく
        self.node_counter = [0 for _ in range(N)]
        # ノードを初期化する
        for v in range(1, N + 1):
            self.adjacency_dict[v] = []

    def add_edge(self, v1, v2):
        """ ノード同士をつなぐ。"""
        # 無向グラフの場合は双方向。もし有向グラフなら片側のみ。
        self.adjacency_dict[v1].append(v2)

    def dfs_rec(self, start, visited=None):
        """再帰的に探索して自身と配下の頂点リストを返す"""
        if visited is None:
            visited = []
        visited.append(start)
        for v in self.adjacency_dict[start]:
            if v in visited:
                continue
            self.dfs_rec(v, visited)
        return visited

    def add_nodes_counter(self, start, x):
        """指定した頂点配下のカウンターをxだけ増やす"""
        vertexes = self.dfs_rec(start)
        # print(f"カウントアップ対象の頂点: {vertexes}")
        for n in vertexes:
            self.node_counter[n - 1] += x


# インスタンス生成
g = Graph()


# 辺のデータを取得
def split_input():
    return map(int, input().split())


for _ in range(N - 1):
    a, b = split_input()
    g.add_edge(a, b)

# print(f"グラフチェック: {g.adjacency_dict}")

# 操作のデータを取得
for _ in range(Q):
    v, x = split_input()
    # print(f"操作: {v, x}")
    g.add_nodes_counter(v, x)

print(" ".join(map(str, g.node_counter)))

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10000000)

class tree:
    def __init__(self):
        self.baby_list=[]
        self.counter=0
    
    def add_value(self):
        for i in self.baby_list:
            hoge[i].counter += self.counter
            hoge[i].add_value()

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


hoge={}

for i in range(1,N+1):
    hoge[i] = tree()
    
for i in range(N-1):
    a,b=input().split()
    hoge[a].baby_list.append(b)

for i in range(Q):
    root, value = input().split()
    hoge[root].counter+=int(value)

hoge[1].add_value()
output = ""
for t in hoge:
    output+=str(hoge[t].counter)+" "

print(output[:-1])

Submission status: Runtime Error

Solution code:

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

edge_map = {}
for i in range(N):
    edge_map[i] = []

for edge in edges:
    a = edge[0]
    b = edge[1]
    edge_map[a-1].append(b-1)
    edge_map[b-1].append(a-1)


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

for operation in operations:
    p = operation[0]
    x = operation[1]
    counters[p-1] += x


res_list = [counters[i] for i in range(N)]
calculated = [False for i in range(N)]

def dfs_res(idx, parent, diff):
    global res_list
    global counters
    if calculated[i]:
        return res_list[idx]
    res = counters[idx] + diff
    res_list[idx] = res
    calculated[idx] = True
    for child in edge_map[idx]:
        if child == parent:
            continue
        dfs_res(child, idx, res)
    return

dfs_res(0, None, 0)

ans = ""
for res in res_list:
    ans += str(res) + " "
print(ans)

Submission status: Runtime Error

Solution code:
n,q=map(int,input().split())
d = {}
ans = [0]*(n+1)
for i in range(n-1):
    sta,gol = map(int,input().split())
    if sta not in d:
        d[sta] = set() 
    d[sta].add(gol)

dv = {}
for i in range(q):
    sta,val = map(int,input().split())
    if sta not in dv:
        dv[sta] = val 
    else:
        dv[sta]+=val
    

#print(d)
#print(dv)  

def cal_(ans_,sta_,flow):
    val_ = flow
    if sta_ in dv:
        val_ +=dv[sta_]
    
    ans_[sta_]+=val_
    
    if sta_ in d:
        targetset = d[sta_]
        for t in targetset:
            ans_=cal_(ans_,t,val_)
    return ans_

ans = cal_(ans,1,0)
    
for i in range(n):
    print(ans[i+1], " ",end="")

Submission status: Runtime Error

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

# pt, oya, ko
ki = [[0, 0, []] for i in range(N)]

def dfs(target, p, x):
  target.extend(ki[p-1][2])
  ki[p-1][0] += x
  target.pop(0)
  
  if len(target) == 0:
    return
  else:
  	dfs(target, target[0], x)

for i in range(N-1):
  a, b = map(int, input().split())
  ki[a-1][2].append(b)
  ki[b-1][1] = a
  
for i in range(Q):
  p, x = map(int, input().split())
  
  target = [p]
  dfs(target, p, x)
  
for i in ki:
  print(str(i[0]), end=" ")

Submission status: Runtime Error

Solution code:
def get_verteces_in_subtree():
    mem = {}
    
    def func(vertex):
        if vertex in mem.keys():
            return mem[vertex]
        
        children = tree_dictionary[vertex]
        if len(children) == 0:
            answer = [vertex]
        else:
            answer = [vertex] + sum([func(child) for child in children], [])
        mem[vertex] = answer
        return answer
    return func
  
  get_verteces_in_subtree = get_verteces_in_subtree()

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

tree_dictionary = {i: [] for i in range(1, N+1)}
for edge in edges:
    tree_dictionary[edge[0]].append(edge[1])

counts = [0] * N
for op in operations:
    top_vertex, value = op
    added_verteces = get_verteces_in_subtree(top_vertex)
    for v in added_verteces:
        counts[v-1] += value

output = ""
for c in counts:
    output += (str(c) + " ")
output = output[:-1]
print(output)

Submission status: Runtime Error

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

class Node:
    def __init__(self, root):
        self.root = root
        self.children = []
        self.val = 0

    def add_child(self, child_node):
        self.children.append(child_node)
        if self.root is not None:
            self.root.add_child(child_node)

nodes = [None] * n
nodes[0] = Node(None)

for i in range(1, n):
    a, b = map(int, input().split())
    a_node = nodes[a - 1]
    if nodes[b - 1] is None:
        b_node = Node(a_node)
        nodes[b - 1] = b_node
    a_node.add_child(nodes[b - 1])

for j in range(q):
    p, x = map(int, input().split())
    node = nodes[p - 1]
    node.val += x
    children = node.children
    for child in children:
        child.val += x

res = []
for node in nodes:
    res.append(str(node.val))
print(" ".join(res))