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:
def job(graph,count,a,b):
	count[a]+=b
	if len(graph[a])!=0:
		for i in range(len(graph[a])):
			job(graph,count,graph[a][i],b)
	return count

n,q=map(int,input().split())
graph=[[] for i in range(n+1)]
for i in range(n-1):
	a,b=map(int,input().split())
	graph[a].append(b)
query=[]
for j in range(q):
	data=list(map(int,input().split()))
	query.append(data)

count=[0 for i in range(n+1)]
for i in range(len(query)):
	a,b=query[i][0],query[i][1]
	count=job(graph,count,a,b)
count.pop(0)
for i in range(len(count)):
	if i!=len(count)-1:
		print(count[i],end=' ')
	else:
		print(count[i])

Submission status: Runtime Error

Solution code:

def count_add(info_lst, pi_xi_sum_lst, output_lst, current_node, adding):
    output_lst[current_node] += adding
    for i in info_lst[current_node]:   #先の枝についても再帰
        adding += pi_xi_sum_lst[i]
        count_add(info_lst, pi_xi_sum_lst, output_lst, i, adding)
        adding -= pi_xi_sum_lst[i]

def glaph_2_tree(info_lst, passed_place, current_node):
    next_nodes_lst = info_lst[current_node][:]
    for next_node in next_nodes_lst:
        if passed_place[next_node]: # 通ったことがあったら、
            info_lst[current_node].remove(next_node)
        else:
            passed_place[next_node] = True
            glaph_2_tree(info_lst, passed_place, next_node)
            passed_place[next_node] = False
    passed_place[next_node] = True

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

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

for _ in range(N-1): # 10**5
    ai, bi = map(int, input().split())
    info_lst[ai].append(bi)
    info_lst[bi].append(ai)

passed_place = [False] * (N+1)
passed_place[1] = True
glaph_2_tree(info_lst, passed_place, 1) # 10**5

pi_xi_sum_lst = [0]*(N+1)
for _ in range(Q): # 10**5
    pi, xi = map(int, input().split())
    pi_xi_sum_lst[pi] += xi

output_lst = [0]*(N+1)
count_add(info_lst, pi_xi_sum_lst, output_lst, current_node=1, adding=pi_xi_sum_lst[1])

output_str = ""
for i in range(1, N+1):
    output_str += str(output_lst[i]) + " "

print(output_str)

Submission status: Runtime Error

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

import numpy as np
import sys
sys.setrecursionlimit(4100000)

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])
point_list = [0]*N
#print(point_list)
for i in range(Q):
    q = list(map(int, input().split()))
    q_tmp = np.where(tree[(q[0]-1):,:] == 1)
    if str(q_tmp[1].shape) == '(0,)':
        point_list[q[0]-1] += int(q[1])
    else:
        for j in q_tmp[1]:
            point_list[j] += int(q[1])
        point_list[q[0]-1] += int(q[1])

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

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

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
#ABC138D
import sys
sys.setrecursionlimit(100000)

tmp = input().split()
n,q = list(map(lambda a: int(a), tmp))

apex=[]
node=[]

#for i in range(0,n+1):
#	node.append([])
#	apex.append(0)
node.append([])
apex.append(0)
node.append([])
apex.append(0)

for i in range(1,n):
	node.append([])
	apex.append(0)
	tmp = input().split()
	hoge = list(map(lambda a: int(a), tmp))
	node[hoge[0]].append(hoge[1])

for i in range(1,q+1):
	tmp = input().split()
	hoge = list(map(lambda a: int(a), tmp))
	apex[hoge[0]]+=hoge[1]

#print(node)
#print(apex)

def calc(j):
	for i in node[j]:
		apex[i]+=apex[j]
		calc(i)

calc(1)
#print(apex)

ans=str(apex[1])
for i in range(2,n+1):
	ans += " " + str(apex[i])
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)  

checked = set()

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

ans = cal_(ans,1,0,checked)

anss = ""
for i in range(n):
    anss = anss+str(ans[i+1])+" "
print(anss)

Submission status: Runtime Error

Solution code:
num, q = [int(s) for s in input().split()]

count = [0 for s in range(num)]
family = [[] for s in range(num)]

for i in range(num-1):
  a, b = [int(s) - 1 for s in input().split()]
  family[a].append(b)

def countup(a,b):
  for k in family[a]:
    count[k] += b
    countup(k,b)

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

answer = str(count[0])
for i in range(num -1):
  answer += " " + str(count[i + 1])
print(answer)

Submission status: Runtime Error

Solution code:
n, q = map(int, input().split())
ans = [0] * n
ki = {1 : [1]}
for _ in range(n - 1):
  a, b = map(int, input().split())
  ki[b] = ki[a] + [b]
ki = ki.values()

p = {}
for _ in range(q):
  c, d = map(int, input().split())
  if c not in p.keys():
    p[c] = d
  else:
    p[c] = p[c] + d

for e, f in p.items():
  for n, k in enumerate(ki):
    if e in k:
      ans[n] += f
  
ans2 = ''
for e in ans:
  ans2 += str(e) + ' '
print(ans2[:-1])

Submission status: Runtime Error

Solution code:
n,q = map(int,input().split())
a=[[] for i in range(n)]
p=[]
l=[0]*n

def plus(tl,ta,t2):
    # print(tl)
    for i in ta:
        tl[i-1]+=t2
        # print(ta[t1-1],t1)
        plus(tl,a[i-1],t2)

for i in range(n-1):
    t1,t2 = map(int,input().split())
    a[t1-1].append(t2)
# print(a)
for i in range(q):
    t1,t2 = map(int,input().split())
    # print(a[t1-1],t1)
    l[t1-1]+=t2
    plus(l,a[t1-1],t2)
    
print(" ".join(map(str,l)))

Submission status: Runtime Error

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

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

parent = [0] * N

#2
for i in range(N):
    parent[i] = [i + 1]
    
    if i != N-1:
        parent[a[i] - 1].append(b[i])
    
# 1
#for i in range(N - 1):
#    parent[a[i] - 1].append(b[i])

# 3
for i in range(N):
    for j in range(len(parent[i])):
        for k in range(len(parent[parent[i][j]-1])):
            parent[i].append(parent[parent[i][j]-1][k])

#4
for i in range(N):
    parent[i] = list(set(parent[i]))

###########33

value = [0] * N

for i in range(Q):
    for j in range(len(parent[p[i]-1])):
        value[parent[p[i]-1][j]] = x[i]
        print(parent[p[i]-1][j])


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

Submission status: Runtime Error

Solution code:
def resolve():
    global N,Q,A,P,Ns,L
    N,Q=map(int,input().split())
    A=[list(map(int,input().split())) for _ in range(N-1)]
    P=[list(map(int,input().split())) for _ in range(Q)]
    Ns={}
    for i in A: Ns.setdefault(i[0],[]).append(i[1])
#        af(i[0],i[1])
    L=[0]*(N)
    for p in P: f(p[0],p[1])
    print(*L)

#def af(b,a):
#    global Ns,A
#    Ns.setdefault(b,[]).append(a)
#    for x in get_keys_from_value(Ns,[b]): #bを含んでるやつ全部に対して再帰
#        af(x,a)

def get_keys_from_value(d, val):
    return [k for k, v in d.items() if v == val]

def f(n,i):
    global L,A,Ns
    L[n-1]+=i
    if len(Ns)<n: return()
    for x in Ns[n]:
        f(x,i)
#        L(x-1)+=i
resolve()

Submission status: Runtime Error

Solution code:
n,q=map(int,input().split())
tree = [set() for _ in range(n)]
for i in range(n-1):
    a,b=map(int,input().split())
    tree[a-1].add(b)
ans=[0]*n
def add_l(x):
    if not tree[x-1]:
        return
    for i in list(tree[x-1]):
        add_l(i)
        tree[x-1] |= tree[i-1]

add_l(1)
#print(tree)

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

        for j in list(tree[p-1]):
            ans[j-1]+=x
print(*ans)

Submission status: Runtime Error

Solution code:
import numpy as np
N,Q = map(int,input().split())
ans = np.array([0]*N)
test = np.array([1]*N)
test = np.diag(test)
p = []
x = []
for i in range(1,N):
    ai,bi = map(int,input().split())
    test[ai-1,bi-1]+=1
for j in range(Q):
    pj,xj = map(int,input().split())
    p.append(pj)
    x.append(xj)

for k in reversed(range(N)):
    check = np.where(test[k] > 0)
    test[k]+=np.sum(test[check],axis=0)
test = np.where(test > 0,1,0)
for j in range(Q):
    ans += test[p[j]-1]*x[j]
print(' '.join(map(str,ans)))

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
stdin = sys.stdin
from functools import lru_cache
 
ns = lambda: stdin.readline().rstrip()
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
s = lambda h: [list(map(int, stdin.readline().split())) for i in range(h)]

n, q = na()
a, b = [0]*n, [0]*n
G = [[] for i in range(n)]
for i in range(n-1):
        a, b = na()
        G[a-1].append(b-1)

seen = [0] * n

def dfs(v):
        seen[v] = True
        for next_v in G[v]:
                if seen[next_v]:
                        continue
                dfs(next_v)
ans = np.zeros(n)
for i in range(q):
        p, x = na()
        seen = np.zeros(n)
        dfs(p-1)
        seen[p-1] = True
        ans += x * seen
ans = ans.astype(np.int32)

print(*ans)

Submission status: Runtime Error

Solution code:
n,q = int(input().split())
a = []
b = []
for i in range(n-1):
  a1,b1=[int(i) for i in input().split()]
  a.append(a1)
  b.append(b1)
p = []
x = []
for j in range(q):
  p1,x1=[int(j) for j in input().split()]
  p.append(p1)
  x.append(x1)
c = [0]*n
for j in range(q):
  for i in range(n-1):
    if p[j] == a[i]:
      c[a[i]-1] += x[j]
      c[b[i]-1] += x[j]
      for l in range(i,n-1):
        if b[i] == a[l]:
          c[a[l]-1] += x[j]
          c[b[l]-1] += x[j]
print(c)

Submission status: Runtime Error

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

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

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

ans = [0] * (n + 1)
visited = [False] * (n + 1)


def walk(e, cnt):
    ans[e] = cnt
    visited[e] = True
    for i in g[e]:
        if not visited[i]:
            walk(i, cnt + c[i])
    return


walk(1, c[1])
print(*ans[1:], sep=" ")

Submission status: Runtime Error

Solution code:
#標準入力
N,Q = list(map(int,input().split()))
tree = []
for i in range(N-1):
  tmp = [int(i) for i in input().split()]
  tree.append(tmp)

x_list = []
for i in range(Q):
  tmp = [int(i) for i in input().split()]
  x_list.append(tmp)

#print(N)
#print(Q)
#print(tree)
#print(x_list)
#関数

#l:リスト　x:加算値
def saiki(result, chil_list, pos, l, x):
  #print(result)
  if not l:
    result[pos] += x
  else:
    result[pos] += x
    for j in l:
      #print(j)
      saiki(result, chil_list, j, chil_list[j], x)
    

#子リストの作成
children=[]
for i in range(N+1):
  children.append([])
for i in range(N-1):
  children[tree[i][0]].append(tree[i][1])

#print(children)
#結果リストの初期化
result = [0] * (N+1)

for i in range(Q):
  kasan_root = x_list[i][0]
  kasan = x_list[i][1]
  
  if not children[kasan_root]:
    result[kasan_root] += kasan
  else:
    saiki(result, children, kasan_root, children[kasan_root], kasan)
    #result[kasan_root] += kasan
  
result.pop(0)
print(*result)

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
nodes = set()
stree = {}
for n in range(N-1):
    a, b = map(int, input().split())
    nodes.add(a)
    if stree.get(a) is None:
        stree[a] = set()
    stree[a].add(b)

memo = {}
def fla(p):
    if memo.get(p) is not None:
        return memo[p]
    cs = stree.get(p)
    if cs is None:
        return None
    subs = set(cs)
    for c in cs:
        r = fla(c)
        if r:
            subs |= memo[c]
    memo[p] = subs
    return subs

x = [0]*N
for q in range(Q):
    node, add = map(int,input().split())
    x[node-1] += add
    if fla(node) is not None:
        for c in fla(node):
            x[c-1] += add
#print(memo)
print(' '.join(map(str, x)))

Submission status: Runtime Error

Solution code:
import sys
f = open('q1input.txt', 'r')
sys.stdin = f

# Setup
import sys
import collections
sys.setrecursionlimit(4100000)

n,q = [int(i) for i in input().split()]
a = [[int(i) for i in input().split()] for _ in range(n-1)]
p = [[int(i) for i in input().split()] for _ in range(q)]

childs = collections.defaultdict(list)

for A,B in a:
    childs[A].append(B)

counter = collections.defaultdict(int)
affections = collections.defaultdict(list)

for A,B in p:
    counter[A] += B
    if affections.get(A):
        continue
    current = A
    aff = []
    tosee = [current]
    while len(tosee) != 0:
        temp = tosee.pop()
        aff.append(temp)
        for z in childs[temp]:
            if affections.get(z):
                aff += affections[z]
            else:
                tosee.append(z)
    affections[A] = aff
counts = collections.defaultdict(int)

Submission status: Runtime Error

Solution code:
n,q=map(int,input().split())
tree = [set() for _ in range(n)]
for i in range(n-1):
    a,b=map(int,input().split())
    tree[a-1].add(b)
ans=[0]*n
def add_l(x):    
    for i in list(tree[x-1]):
        add_l(i)
        tree[x-1] |= tree[i-1]

add_l(1)
#print(tree)

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

        for j in list(tree[p-1]):
            ans[j-1]+=x
print(*ans)

Submission status: Runtime Error

Solution code:
from collections import deque
import copy

N, Q = map(int, input().split())
a_b_list = []
input_dic = {}
score_dic = {}

for i in range(0, N-1):
    a, b = map(int, input().split())
    a_b_list.append((a, b))
    score_dic[a] = 0
    score_dic[b] = 0
    if a in input_dic:
        l = input_dic[a]
        l.append(b)
        input_dic[a] = l
    else:
        l = [b]
        input_dic[a] = l

p_x_list = []
for i in range(0, Q):
    p, x = map(int, input().split())
    p_x_list.append((p, x))


def addPoint(position, point):
    global  score_dic
    score_dic[position] = score_dic[position] + point

    if position not in input_dic:
        return

    for next_position in input_dic[position]:
        addPoint(next_position, point)


for (position, point) in p_x_list:
    addPoint(position, point)

sorted_score = sorted(score_dic.items())

r = []
for k, v in sorted_score:
    r.append(str(v))
print(' '.join(r))

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
flim = n-1
for i in range(flim):

    # 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
    flim = len(sdict[p])
    for j in range(flim):
        anslist[sdict[p][j]] += x

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

Submission status: Runtime Error

Solution code:
n,q = map(int,input().split())
a=[[] for i in range(n)]
p=[]
l=[0]*n

def plus(tl,ta,t2):
    # print(tl)
    for i in ta:
        tl[i-1]+=t2
        # print(ta[t1-1],t1)
        plus(tl,a[i-1],t2)

for i in range(n-1):
    t1,t2 = map(int,input().split())
    a[t1-1].append(t2)
# print(a)
for i in range(q):
    t1,t2 = map(int,input().split())
    # print(a[t1-1],t1)
    l[t1-1]+=t2
    plus(l,a[t1-1],t2)
    



print(l)

Submission status: Runtime Error

Solution code:
class Tree:
  def __init__(self,oya):
    self.ko = []
    self.oya = oya
    self.cnt = 0
  def add_ko(self,a):
    self.ko.append(a)
   
  def set_oya(self,oya):
    self.oya = oya
   
  def get_ko(self):
    return self.ko
  
  def get_cnt(self):
    return self.cnt
  
  def add_cnt(self,cnt):
    self.cnt += cnt
    
def add_cnt_t(no,index,cnt):
  no[index].add_cnt(cnt)
  for i in no[index].get_ko():
    add_cnt_t(no,i,cnt)
    
N,Q = map(int,input().split())

node = []
for i in range(N):
  node.append(Tree(-1))

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

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

for i in range(N):
  print(node[i].get_cnt(),end=" ")

Submission status: Runtime Error

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

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

class Node():
    def __init__(self):
        self.children = []
        self.count = 0

G = [Node() for _ in range(N)]
for _ in range(N-1):
    p, c = map(int, input().split())
    G[p-1].children.append(c-1)

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

def add_count(v):
    for child in G[v].children:
        G[child].count += G[v].count
        add_count(child)

add_count(0)

counts = [node.count for node in G]
print(*counts)

Submission status: Runtime Error

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

class node():
  def __init__(self):
    self.counter = 0
    self.children = []
  def child_add(self, child):
    self.children.append(child)

def go_around_add(nodes, c, x):
  nodes[c].counter += x
  if not nodes[c].children:
    return
  else:
    for cc in nodes[c].children:
      go_around_add(nodes, cc, x)

# node create
nodes = []
for n in range(N):
  nn = node()
  nodes.append(nn)

# set children
for n in range(N - 1):
  a, b = list(map(int, input().split()))
  m = a - 1
  nodes[m].child_add(b - 1)

# add counter
for q in range(Q):
  p, x = list(map(int, input().split()))
  pp = p - 1
  go_around_add(nodes, pp, x)

ttt = list(map(lambda x: x.counter, nodes))
print(' '.join(map(str, ttt)))

Submission status: Runtime Error

Solution code:
def tree_add(tree, p, ans, num):
    ans[p] += num
    if tree[p]:
        for i in tree[p]:
            tree_add(tree, i, ans, num)

n, q = map(int, input().split())
tree = [[] for i in range(n)]
ans = [0] * n

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

for i in range(q):
    p, x = map(int, input().split())
    p -= 1
    tree_add(tree, p, ans, x)

print(*ans)

Submission status: Runtime Error

Solution code:
import numpy as np

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


class Graph:
    def __init__(self):
        """ ノードのつながりを辞書型で表現する """
        self.adjacency_dict = {}
        # 頂点カウンターを用意しておく
        # self.node_counter = [0 for _ in range(N)]
        self.node_counter = np.zeros(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 = np.array(self.dfs_rec(start))
        vertexes -= 1
        # print(f"カウントアップ対象の頂点: {vertexes}")
        # for n in vertexes:
        #     self.node_counter[n - 1] += x
        self.node_counter[vertexes] += 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(lambda x: str(int(x)), g.node_counter)))

Submission status: Runtime Error

Solution code:
child = {}
parent = {}
node_list = set()
for ab in a_b:
    parent[ab[1]] = ab[0]
    child[ab[0]] = child.get(ab[0], [])
    child[ab[0]].append(ab[1])
    node_list.add(ab[0])
    node_list.add(ab[1])

for k, v in child.items():
    if k != 1:
        child[parent[k]] += v
        
sorted_nodes = sorted(list(node_list))

print("test")

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 = []

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

for i in range(n-1):
    temp1, temp2 = map(int, input().split())
    a.append(temp1)
    b.append(temp2)
    nodeParent = nodes[a[i]]
    nodeChild = nodes[b[i]]
    nodeParent.child.append(nodeChild)

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

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

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

def printNode(node):
    for i in range(1, n+1):
        ans.append(nodes[i].point)

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:
from collections import defaultdict

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

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

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


def dfs(e, v, x):
    seen[v] = True
    ans[v] += x
    for next_v in e[v]:
        if seen[next_v]:
            continue
        else:
            dfs(e, next_v, x + q[next_v])


dfs(e, 1, q[1])

print(*ans[1:])

Submission status: Runtime Error

Solution code:
#標準入力
N,Q = list(map(int,input().split()))
tree = []
for i in range(N-1):
  tmp = [int(i) for i in input().split()]
  tree.append(tmp)

x_list = []
for i in range(Q):
  tmp = [int(i) for i in input().split()]
  x_list.append(tmp)

#print(N)
#print(Q)
#print(tree)
#print(x_list)
#関数
  
def subtree(subtree, x):
  for node in subtree:
    result[node] += x

#l:リスト　x:加算値
def saiki(result, chil_list, pos, l, x):
  #print(result)
  if not l:
    result[pos] += x
  else:
    result[pos] += x
    for j in l:
      #print(j)
      saiki(result, chil_list, j, chil_list[j], x)
    

#子リストの作成
children=[]
for i in range(N+1):
  children.append([])
for i in range(N-1):
  children[tree[i][0]].append(tree[i][1])

#print(children)
#結果リストの初期化
result = [0] * (N+1)

for i in range(Q):
  kasan_root = x_list[i][0]
  kasan = x_list[i][1]
  
  if not children[kasan_root]:
    result[kasan_root] += kasan
  else:
    saiki(result, children, kasan_root, children[kasan_root], kasan)
    #result[kasan_root] += kasan
  
result.pop(0)
print(*result)

Submission status: Runtime Error

Solution code:
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces


def calc(p, x, li, ans):
    ans[p] += x
    l = len(li[p])
    for i in range(l):
        calc(li[p][i], x, li, ans)


n, q = na()
li = [[] for i in range(n)]
ans = [0 for j in range(n)]

for i in range(n-1):
    a, b = na()
    li[a-1].append(b-1)

for j in range(q):
    p, x = na()
    calc(p-1, x, li, ans)
print(*ans)

Submission status: Runtime Error

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

ki = [[] for i in range(n+1)]
for i in range(n-1):
    hida,migi = list(map(int, input().split()))
    ki[hida].append(migi)

p = [0] * (n+1)
for i in range(q):
    pp,xx = list(map(int, input().split()))
    p[pp] += xx

# print("ki",ki)
# print("p",p)

list_n = [0] * (n+1)
list_s = [0] * (n+2)
ind = 0

def adddd(num):
    global ki
    global list_n
    global list_s
    global ind

    list_n[ind] = num
    list_s[ind] += p[num]

    if ( len(ki[num]) > 0):
        for ko in ki[num]:
            ind += 1
            adddd(ko)
    list_s[ind+1] -= p[num]

adddd(1)

# print("n",list_n)
# print("s",list_s)

tmp = 0
list_ss = [0] * (n+2)

for i,si in enumerate(list_s):
    tmp += si
    list_ss[i] = tmp

#print("ss",list_ss)

list_rtn = [0] * n
for i in range(n):
    list_rtn[list_n[i] - 1] = list_ss[i]

print(*list_rtn)

Submission status: Runtime Error

Solution code:
def repeat(index, cost):
    if index in dict_tree:
        if set(cost) == set(dict_tree[index]):
            return
        else:
            for k in (set(dict_tree[index]) - set(cost)):
                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)
    point[p-1] += x
    repeat(p, cost)

for m in point:
    print(m)

Submission status: Runtime Error

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

def find(nodes, key):
  if len(nodes[key]) == 1:
    return [key]
  else:
    x = [key]
    for node in nodes[key]:
      if key != node:
        x.extend(find(nodes, node))
    return x

nodes = {}
nodes_p = {}
for _ in range(N-1):
  a,b = map(int, input().split())
  if a in nodes:
    nodes[a].append(b)
  else:
    nodes_p[a] = 0
    nodes[a] = [a]
    nodes[a].append(b)

  if b not in nodes:
    nodes_p[b] = 0
    nodes[b] = [b]

for key in nodes:
  nodes[key] = find(nodes, key)

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

print(" ".join(map(str, [ v for v in nodes_p.values()])))

Submission status: Runtime Error

Solution code:
import numpy as np
import sys

def main():
    n, q = map(int, input().split())
    ab = [[],[]]
    
    for i in range(n-1):
        na,nb = map(int, input().split())
        ab[0].append(na)
        ab[1].append(nb)

    px = [[],[]]
    for i in range(q):
        np,nx = map(int, input().split())        
        px[0].append(np)
        px[1].append(nx)
    
    # print(n,q,ab,px)
    count = [0 for i in range(n)]

    lgth = max(ab[0])
    node =[[] for i in range(lgth)]
    for i in range(n-1):
        index = ab[0][i]-1
        put = ab[1][i]
        node[index].append(put)

    # print(node)
    def calc(idx,val):
        count[idx] += val

        if idx <= lgth-1:
            for j in node[idx]:
                calc(j-1,val)
        
    for i in range(len(px[0])):    
        calc(px[0][i]-1, px[1][i])
    
    print(' '.join(map(str,count)))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
l = [ int(i) for i in input().split()]
N = l[0]
Q = l[1]
tree = [[] for i in range(N+1)]
val = [0 for i in range(N+1)]
ans = [0 for i in range(N+1)]
p = []
O = []
for i in range(N-1):
    p = [int(i) for i in input().split()]
    #print(i)
    tree[p[0]].append(p[1])
    tree[p[1]].append(p[0])

for i in range(Q):
    O = [int(i) for i in input().split()]
    val[O[0]] += O[1]
cur = 0
def trace(son,fa):
    global cur
    cur += val[son]
    ans[son]=cur
    for i in tree[son]:
        if i == fa:
            continue
        trace(i,son)
    cur -= val[son]

trace(1,0)
a = ''
for i in range (1, N+1) :
    a += str(ans[i])+' '
print(a)

Submission status: Runtime Error

Solution code:
import numpy as np

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


#c = np.zeros((n+1,n+1))


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:
n, q = map(int, input().split())

# 各ノードのリンクを記録
link_list = [[] for i in range(n-1)]
for i in range(n-1):
  a, b = map(int, input().split())
  link_list[a - 1].append(b)
  
# 各ノードの部分木の全てのノードをリストアップ
link_set = [set() for i in range(n-1)]
for i in range(n-1, 0, -1):
  link_set[i - 1] = set(link_list[i - 1])
  if i < n-1:
    for j in link_list[i - 1]:
      if j < n - 1:
        link_set[i - 1] = link_set[i - 1] | link_set[j - 1]

# カウンターの計算を実施
counters = [0] * n
for i in range(q):
  p, x = map(int, input().split())
  counters[p - 1] += x
  for node in link_set[p - 1]:
    counters[node - 1] += x
str_counters = [str(c) for c in counters]
print(' '.join(str_counters))