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:
# -*- coding: utf-8 -*-
import numpy as np

def forward(matrix, plus, pos, counter):
    for i in range(pos+1,N):
        val = matrix[pos,i]
        if val == 1:
            counter[i] += plus
            save = pos
            pos = i
            forward(matrix, plus, pos, counter)
            pos = save


if __name__ == '__main__':
    N, Q = map(int, input().split())

    matrix = np.zeros((N,N))
    counter = []
    for i in range(N):
        counter.append(0)

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

    P, X = [], []
    for i in range(Q):
        p, x = map(int, input().split())
        P.append(p-1)
        X.append(x)

    for p, x in zip(P,X):
        counter[p] += x
        forward(matrix, x, p, counter)

    out = str(counter[0])
    for i in range(len(counter)-1):
        out = out + ' ' + str(counter[i+1])

    print(out)

Submission status: Runtime Error

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

from collections import defaultdict

N, Q = map(int, input().split())
ab = [tuple(map(int, input().split())) for _ in range(N-1)]
px = [tuple(map(int, input().split())) for _ in range(Q)]

parent_map = {b: a for a, b in ab}
child_map = defaultdict(list)
for parent, child in ab:
    child_map[parent].append(child)

operation_map = defaultdict(int)
for p, x in px:
    operation_map[p] += x

counter = [0] * N


def count(parent_no, parent_counter):
    for child_no in child_map[parent_no]:
        child_count = parent_counter + operation_map[child_no]
        counter[child_no-1] = child_count
        count(child_no, child_count)


counter[0] = operation_map[1]
count(1, counter[0])

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

Submission status: Runtime Error

Solution code:
a,b=map(int,input().split())
y=[]
for i in range(a-1):
    v=list(map(int,input().split()))
    y.append(v)
y.sort(key=lambda net:net[0])
ans=[0]*a
for j in range(b):
    c,d=map(int,input().split())
    ans[c-1]=ans[c-1]+d
for k in range(a-1):
    ans[zz]=ans[y[k][1]-1]+ans[y[k][0]-1]
print(*ans,sep=" ")

Submission status: Runtime Error

Solution code:
vimport sys
sys.setrecursionlimit(1000000)
n, q = map(int,input().split())
d = {}
for i in range(n-1):
    ai, bi = map(int,input().split())
    if ai-1 in d:
        d[ai-1] += [bi-1]
    else:
        d[ai-1] = [bi-1]
    if bi-1 in d:
        d[bi-1] += [ai-1]
    else:
        d[bi-1] = [ai-1]
#point
px = [0 for i in range(n)]
for i in range(q):
    pi,xi = map(int,input().split())
    px[pi-1] +=xi
sp = [0 for i in range(n)]

def f(v,vp,p):
    su = p + px[v]
    sp[v] = su
    for di in d[v]:
        if not di == vp:
            f(di,v,su)
f(0,0,0)
for i in range(n):
    print(sp[i])

Submission status: Runtime Error

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

add_lis = [0] * N
ans_lis = [0] * N
v_lis = [None] * N
ab_lis = []

for i in range(N-1):
	a = []
	v_lis[i] = a

for i in range(N-1):
	ai,bi = map(int, input().split())
	ab_lis.append((ai,bi))
	v_lis[ai-1].append(bi-1)

for i in range(Q):
	pi,xi = map(int, input().split())
	add_lis[pi-1] += xi

def traverse(i, add_v):
	ans_lis[i] += add_v
	if v_lis[i] != None:
		for n in v_lis[i]:
			traverse(n, add_v)
	return

for i in range(N):
	traverse(i, add_lis[i])

print(" ".join(map(str,ans_lis)))

Submission status: Runtime Error

Solution code:
def resolve():
    global N,Q,A,P,Ns,L
    N,Q=map(int,input().split())
#    for i in range(N):
#        a,b=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)]
#    print()
#    print('N,Q:',N,Q) 
#    print('A:',A)
#    print('P:',P)
#    print('==========')
    Ns={}
    for i in A:
        Ns.setdefault(i[0],[]).append(i[1])
#    print(Ns)
    L=[0]*(N)
#    print('L',L)
    for p in P:
        f(p[0],p[1])
#    print('L',L)
    print(*L)

def f(n,i):#ノード番号,数
    global L,A,Ns
    L[n-1]+=i
    if len(Ns)<n:
        return()
    for x in Ns[n]:
#        print(x,i)
        f(x,i)
resolve()

Submission status: Runtime Error

Solution code:
n, q = map(int, input().split())
# [[parents]]
tree = [[] for _ in range(n)]
for _ in range(n-1):
  a, b = map(int, input().split())
  if a == 1:
    tree[b-1] = [1]
  elif b == 1:
    tree[a-1] = [1]
  
  elif len(tree[a-1]) == 0:
    tree[a-1] = tree[b-1].copy()
    tree[a-1].append(b)
  elif len(tree[b-1]) == 0:
    tree[b-1] = tree[a-1].copy()
    tree[b-1].append(a)

tr = [[] for _ in range(n)]
for i, row in enumerate(tree):
  for x in row:
    tr[x].append(i+1)

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

Submission status: Runtime Error

Solution code:
def acinput():
    return list(map(int, input().split(" ")))


def search(n):
    global P,res,visited
    
    visited[n]=True
    for l in L[n]:
        if not visited[l]:
            res[l]=res[n]+P[l]
            search(l)

N,Q=acinput()

L=[[]for i in range(N+1)]
visited=[False]*(N+1)
for i in range(N-1):
    tmp=acinput()
    L[tmp[0]].append(tmp[1])
    L[tmp[1]].append(tmp[0])

P=[0]*(N+1)
for i in range(Q):
    tmp=acinput()
    P[tmp[0]]+=tmp[1]

res=[0]*(N+1)
res[1]=P[1]
search(1)

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

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)
   
    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:
from sys import stdin, setrecursionlimit

setrecursionlimit(200000)

n, q = [int(x) for x in input().split()]

tree = [[] for _ in range(n + 1)]
cnt = [0] * (n + 1)

for _ in range(n - 1):
    a, b = [int(x) for x in stdin.readline().split()]
    tree[a].append(b)

# TLE/RE

def walk(p, x):
    cnt[p] += x
    for n in tree[p]:
        walk(n, x)


for _ in range(q):
    p, x = [int(x) for x in stdin.readline().split()]
    walk(p, x)

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

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
A = [0]*(N-1)
B = [0]*(N-1)
P = [0]*Q
X = [0]*Q

for i in range(N-1):
    A[i], B[i] = map(int, input().split())

for i in range(Q):
    P[i], X[i] = map(int, input().split())

# print(N, Q, A, B, P, X)

C = {}
for i in range(N - 1):
    a = A[i]
    b = B[i]
    if a > b:
        a, b = b, a
    if a not in C:
        C[a] = {'r': [b], 's': 0}
    else:
        C[a]['r'].append(b)
# print(C)

for i in range(Q):
    p = P[i]
    x = X[i]
    if p not in C:
        C[p] = {'r':[], 's': x}
    else:
        C[p]['s'] += x

# print(C)

# for i in range(1, N):
#     if i not in C:
#         continue
#     c = C[i]
#     R = c['r']
#     s = c['s']
#     for r in R:
#         if r not in C:
#             C[r] = {'r': [], 's': s}
#         else:
#             C[r]['s'] += s

def solve(C, c):
    R = c['r']
    s = c['s']
    for r in R:
        if r not in C:
            C[r] = {'r': [], 's': s}
        else:
            C[r]['s'] += s
        solve(C, C[r])

solve(C, C[1])


# print(C)

ans = []
for i in range(1, N + 1):
    c = C[i]
    ans.append(c['s'])

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

Submission status: Runtime Error

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

add_lis = [0] * N
ans_lis = [0] * N
v_lis = [None] * N
ab_lis = []

for i in range(N-1):
	a = []
	v_lis[i] = a

for i in range(N-1):
	ai,bi = map(int, input().split())
	ab_lis.append((ai,bi))
	v_lis[ai-1].append(bi-1)

for i in range(Q):
	pi,xi = map(int, input().split())
	add_lis[pi-1] += xi

def traverse(i, add_v):
	print("tv: i={}".format(i))
	ans_lis[i] += add_v
	if v_lis[i] != None:
		for n in v_lis[i]:
			traverse(n, add_v)
	return

for i in range(N):
	print("main: i={}".format(i))
	traverse(i, add_lis[i])

print(" ".join(map(str,ans_lis)))

Submission status: Runtime Error

Solution code:
import sys
import collections


def main():
    [n, q] = [int(s) for s in sys.stdin.readline().strip().split()]
    a = [-1] * (n-1)
    b = [-1] * (n-1)
    tree = collections.defaultdict(set)
    for i in range(n-1):
        a[i], b[i] = [int(s) for s in sys.stdin.readline().strip().split()]
        tree[a[i]-1].add(b[i]-1)

    p = [-1] * q
    x = [-1] * q
    adds = [0] * n
    for i in range(q):
        p[i], x[i] = [int(s) for s in sys.stdin.readline().strip().split()]
        adds[p[i]-1] += x[i]

    results = [0] * n
    seen = set()

    def rec_add(node, cur):
        if node in seen:
            return
        cur += adds[node]
        results[node] = cur
        seen.add(node)
        for child in tree[node]:
            rec_add(child, cur)

    rec_add(0, 0)
    print(' '.join([str(n) for n in results]))


main()

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10000)

n, q = map(int, input().split())
tl = [list() for _ in range(n)]
ans = [0] * n

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

def rec(p, x):
    ans[p-1] += x
    for num in tl[p-1]:
        rec(num, x)

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

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

Submission status: Runtime Error

Solution code:
n, q = map(int, input().split())
ab = [list(map(int, input().split())) for i in range(n-1)]
px = [list(map(int, input().split())) for i in range(q)]

cnt = [0] * n
tree = {}
subt = {}
for i in range(n-1):
    tree.setdefault(ab[i][0], [])
    tree[ab[i][0]].append(ab[i][1])

def pt(node, subt):
    if not node in subt:
        part = []
        if node in tree:
            for i in range(len(tree[node])):
                part += pt(tree[node][i], subt)
        subt.setdefault(node, [node]+part)
    return subt[node]

for i in range(q):
    for j in pt(px[i][0], subt):
        cnt[j-1] += px[i][1]
print(" ".join(map(str, cnt)))

Submission status: Runtime Error

Solution code:
N,Q = map(int,input().split())
ab = []
a=[]
for n in range(N-1):
    ab.append([int(i) for i in input().split()])
px = []
for q in range(Q):
    px.append([int(i) for i in input().split()])
class Graph():
    def __init__(self):
        """ ノードのつながりを辞書型で表現する """
        self.adjacency_dict = {}
    
    def add_vertex(self, v):
        """ ノードを追加する """
        self.adjacency_dict[v] = []
    def add_edge(self, v1, v2):
        """ ノード同士をつなぐ。"""
        # 無向グラフの場合は双方向。もし有向グラフなら片側のみ。
        self.adjacency_dict[v1].append(v2)    
    def print_graph(self):
        print(self.adjacency_dict)
graph = Graph()
for n in range(N-1):
    if graph.adjacency_dict.get(ab[n][0]):
        pass
    else:
        graph.add_vertex(ab[n][0])
    graph.add_edge(ab[n][0],ab[n][1])
def search(graph,j,ret):
    if graph.get(j):
        for k in graph[j]:
            ret.append(k)
            search(graph,k,ret)
    return ret
values = [0]* N
for q in range(Q):
    add_list = search(graph.adjacency_dict,px[q][0],[px[q][0]])
    for add in add_list:
        values[add-1] += px[q][1]
print(' '.join(map(str, values)))

Submission status: Runtime Error

Solution code:
N, Q = [int(x) for x in input().split()]
ab_list = [[int(x) for x in input().split()] for _ in range(N-1)]
px_list = [[int(x) for x in input().split()] for _ in range(Q)]
to = [[] for _ in range(N+1)]
for a, b in ab_list:
    to[a].append(b)
subtree = [[i] for i in range(N+1)]
def dfs(r, i):
    if (len(to[i])):
        for j in to[i]:
            subtree[r].append(j)
            dfs(r, j)
    else:
        return
for i in range(1, N):
    dfs(i, i)

ans = [0 for _ in range(N)]
for p, x in px_list:
    for u in subtree[p]:
        ans[u-1] += x
print(' '.join([str(i) for i in ans]))

Submission status: Runtime Error

Solution code:
from collections import defaultdict
n,q=map(int,input().split())
Edges=defaultdict(list)
for _ in range(n-1):
    a,b=map(int,input().split())
    Edges[a-1].append(b-1)
Nodes = [0]*n
for _ in range(q):
    p,x=map(int,input().split())
    Nodes[p-1] += x

def dfs(v,preval,Edges,Nodes,visited): 
    if v < len(visited):
        visited[v]= True
    if v!=0 and v < len(Nodes):
        Nodes[v] += preval
    preval = Nodes[v]

    if v in Edges:
        for i in Edges[v]:
            if i < len(visited):
                if visited[i] == False: 
                    dfs(i,preval,Edges,Nodes,visited) 
    return Nodes

visited = [False]*(len(Nodes)) 
Nodes = dfs(0,Nodes[0],Edges,Nodes,visited) 

print(" ".join(list(map(str,Nodes))))

Submission status: Runtime Error

Solution code:
import copy
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(stree, p):
    cs = stree.get(p)
    if cs is None:
        return None
    if memo.get(p) is not None:
        return memo[p]
    subs = set(cs)
    for c in cs:
        r = fla(stree, c)
        if r is not None:
            subs |= r
        else:
            subs.add(c)
    memo[p] = subs
    return subs

x = [0]*N
# flatten
node_fla = {}
for a in nodes:
    node_fla[a] = fla(stree, a)

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

Submission status: Runtime Error

Solution code:
n, q = map(int, input().split())
B = [[] for _ in range(n+1)]

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

P = []
C = [0]*(n+1)

def add_point(C, p, x):
    C[p] += x

    V = B[p]
    for v in V:
        C = add_point(C, v, x)
    return C


for _ in range(q):
    p, x = map(int, input().split())
    P += [(p, x)]
    C = add_point(C, p, x)

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

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

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


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

    stack = []
    ans[p-1] += x
    for i in range(n+1):
        if g[p][i] == 1:
            stack.append(i)

    while True:
        if len(stack) <= 0:
            break
        #pop = stack.pop(-1)
        pop = stack.pop(0)

        #print(p)
        ans[pop-1] += x
        for i in range(n+1):
            if g[pop][i] == 1:
                stack.append(i)

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

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(100000)

n, q = map(int, input().split())
dic = {}

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

v_list = [0 for _ in range(n)]


def add_v(num, value):
    v_list[num - 1] = v_list[num - 1] + value
    if num in dic:
        for root in dic[num]:
            add_v(root, value)


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

print(*v_list)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python

def search(i):
    global edge, child, visit
    work= {i}
    visit[i]= True
    #
    for e in edge[i]:
        if visit[e]: continue
        work|= search(e)
    #
    child[i]= work
    return work

import sys

n,q = [ int(x) for x in sys.stdin.readline().strip().split() ]
n1= n-1
#
edge= [ [] for _ in range(n) ]
for i in range(n1):
    a,b = [ int(x)-1 for x in sys.stdin.readline().strip().split() ]
    edge[a].append( b )
    edge[b].append( a )
#

visit= [ False for _ in range(n) ]
child= [ set() for _ in range(n) ]
search(0)
#
query= dict()
for i in range(q):
    p,x= [ int(x) for x in sys.stdin.readline().strip().split() ]
    query[p-1]= query.get(p-1,0) + x
#
score= [ 0 for _ in range(n) ]
for p,x in query.items():
    for v in child[p]: score[v]+= x
#
for s in score: print( s,end= " " )

Submission status: Runtime Error

Solution code:
 
def dfs(a, b):  

    visited[a] = 1 
    b += 1
    start[a] = b  
    dfs_order.append(a)  
      
    for it in adj[a]:  
        if not visited[it]:  
            b = dfs(it, b)  
       
    endd[a] = b 
    return b 
  
n, q  = map(int, input().split())
start = [None] * (n+1) 
endd = [None] * (n+1)
dfs_order = []  
adj = [[] for i in range(n+1)]  
visited = [False] * (n+1)
for i in range(n-1):
    a, b = map(int, input().split())
    adj[a-1].append(b-1)

dfs(0, 0)  

subtree = [[] for _ in range(n+1)]
for i in range(n):  
    subtree[i].append(i)  
    if start[i] != endd[i]:   
        for j in range(start[i]+1, endd[i]+1):  
            subtree[i].append(dfs_order[j-1])   

ans = [0]*(n)

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

print(*ans)

Submission status: Runtime Error

Solution code:
def f(t_index,result,s):
    if t_index in t_keys:
        for one in tree_dict[t_index]:
            f(one,result,s)
    result[t_index] += s
            
n,q = map(int,input().split())
tree_dict = dict()
tree_parent = dict()
for i in range(n-1):
    tmp =  list(map(int,input().split()))
    try:
        tree_dict[tmp[0]] = tree_dict[tmp[0]] + [tmp[1]]
    except KeyError:
        tree_dict[tmp[0]] = [tmp[1]] 
        
    tree_parent[tmp[1]]  = tmp[0]
        
    
    
    
        

score = dict()
for i in range(q):
    tmp = list(map(int,input().split()))
    try:
        score[tmp[0]] += tmp[1]
    except KeyError:
        score[tmp[0]] = tmp[1]


t_keys = set(tree_dict.keys())
s_keys = set(score.keys())
result = [0 for _ in range(n+1)]
for one in s_keys:
    s = score[one]
    if one in t_keys:
        for t_index in tree_dict[one]:
            f(t_index,result,s)
        result[one] += s 
    else:
        result[one] += s
        
tmp_str = ""
for one in result[1:]:
    tmp_str += str(one) + " "
tmp_str = tmp_str[:-1]
print(tmp_str)

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
    if len(li[p]) == 0:
        return
    for b in li[p]:
        calc(b, x, li, ans)

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

for i in range(q):
    p, x = na()
    calc(p, x, li, ans)
print(*ans[1:])

Submission status: Runtime Error

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

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

class Node():
    def __init__(self):
        self.parent = -1
        self.children = []
        self.depth = -1
        self.count = 0

def dfs(G, v=0, d=0):
    G[v].depth = d
    for child in G[v].children:
        dfs(G, child, d+1)

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

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

dfs(G)

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

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

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):
  if len(family[a]) > 0:
    for k in family[a]:
      count[k] += b
      if len(family[k]) > 0:
        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:

def count_add(info_dic, pi, xi):
    info_dic[pi][0] += xi
    for i in info_dic[pi][1]:   #先の枝についても再帰
        count_add(info_dic, i, xi)

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

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

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

for _ in range(N-1):
    ai, bi = map(int, input().split())
    info_dic[ai][1].append(bi)
    info_dic[bi][1].append(ai)

passed_place = [False] * (N+1)
passed_place[1] = True
glaph_2_tree(info_dic, passed_place, 1)
#print() ##################
for _ in range(Q):
    pi, xi = map(int, input().split())
    count_add(info_dic, pi, xi)


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

print(output_str)

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 a not in T.keys():
		T[a] = []
	T[a].append(b)

def change(a, v):
	if a not in T.keys():
		V[a] += v
		return
	else:
		V[a] += v
		for x in T[a]:
			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:
from collections import defaultdict
from collections import deque

def setD(d, N):
    for i in range(N):
        d[i] = setsub(d, i)
            
def setsub(d, i):
    tmp = deque()
    for x in d[i]:
        tmp.append(x)
        if d[x] != 0:
            tmp += setsub(d, x)
    return tmp

N, Q = map(int, input().split())
d = defaultdict(deque)

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

setD(d, N)

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

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


for i in range(N):
    ans[i] = str(ans[i])
print(" ".join(ans))

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(100000)
n,q = map(int,input().split())
dic = {}

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

v_list = [0 for _ in range(n)]
print(dic)


def add_v(num, value):
    v_list[num] = v_list[num]+value
    if num in dic:
        for root in dic[num]:
            add_v(root-1, value)


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

print(*v_list)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(1000)

n, q = map(int, input().split())
tl = [list() for _ in range(n)]
ans = [0] * n

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

def rec(p, x):
    ans[p-1] += x
    for num in tl[p-1]:
        rec(num, x)

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

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

Submission status: Runtime Error

Solution code:
/*input
4 3
1 2
2 3
2 4
2 10
1 100
3 1
hooded_sweater   
*/

#include <bits/stdc++.h>
using namespace std;
#define fast_io() ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define all(x) x.begin(), x.end()
#ifndef ONLINE_JUDGE
#define debug(...) cout << "debug: " << #__VA_ARGS__ " = "; _dbg(__VA_ARGS__);
#define debuga(arr, n) _dbga(arr, n, #arr)
#else
#define debug(...)
#define debuga(arr, n)
#endif
typedef long long int ll;
#define int ll
#define F first
#define S second
#define float double
const int inf = LLONG_MAX;
typedef double db;
typedef vector<int> vi;
typedef pair<int, int> pii;

const int mod = 1e9+7;
const int N = 1e6+1;

using namespace std;

vector<ll> adj[N], counter(N);
void bfs(int s) {
  queue<int> q;
  vector<bool> used(N);
  vector<int> d(N), p(N);

  q.push(s);
  used[s] = true;
  p[s] = -1;
  while (!q.empty())
  {
    int v = q.front();
    q.pop();
    for (int u : adj[v])
    {
      if (!used[u])
      {
        counter[u] += counter[v];
        used[u] = true;
        q.push(u);
        d[u] = d[v] + 1;
        p[u] = v;
      }
    }
  }
}

int32_t main() {
  fast_io();

  int n, q; cin >> n >> q;
  for (int i = 0; i < n-1; i++) {
    int u, v; cin >> u >> v;
    adj[u].push_back(v);
    adj[v].push_back(u);
  }
  while (q--) {
    int p, x; 
    cin >> p >> x;
    counter[p] += x;
  }
  bfs(1);
  for (int i=1; i < n+1; i++) {
    cout << counter[i] << " ";
  }

  return 0;
}

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)
print(family)
def countup(a,b):
  if len(family[a]) > 0:
    for k in family[a]:
      count[k] += b
      if len(family[k]) > 0:
        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:
class Node:
    def __init__(self, data): #コンストラクタ
        self.data = data 
        self.kodomo = []
        self.cnt = 0

def saiki(target,tasu):
  #target = array[]
  target.cnt += tasu
  for ko in target.kodomo:
    if array[ko]:
      saiki(array[ko],tasu)
  
        
n, q = [int(i) for i in input().split()]
array=[]

for i in range(n):
  array.append(Node(i+1))
  
  
for i in range(n-1):
  a,b = [int(i) for i in input().split()]
  array[a-1].kodomo.append(b-1)

#でばっぐ
#for i in range(n):
#  print(array[i].kodomo)
  
for i in range(q):
  x, tasu = [int(i) for i in input().split()]
  saiki(array[x-1],tasu)
  
for i in range(n):
  if i != n-1:
    print(array[i].cnt, end =" ")
  else:
    print(array[n-1].cnt)

Submission status: Runtime Error

Solution code:
from functools import lru_cache

@lru_cache(maxsize=4092)
def get_verteces_in_subtree(vertex):
    children = tree_dictionary[vertex]
    if len(children) == 0:
        return [vertex]
    return [vertex] + sum([get_verteces_in_subtree(child) for child in children], [])

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())
A = [[] for i in range(N)]
P = []
X = []
c = [0]*N
def add(p, x):
    for a in A[p]:
        c[a] += x
        add(a, x)

for i in range(N-1):
    a, b = map(int, input().split())
    A[a-1].append(b-1)
for i in range(Q):
    p, x = map(int, input().split())
    P.append(p-1)
    X.append(x)
for i in range(Q):
    p = P[i]
    x = X[i]
    c[p] += x
    add(p, x)
print(' '.join(map(str,c)))

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)
   
    for j in q_tmp[1]:
        point[j] += q[1]
    point[q[0]-1] += q[1] 

point = point.tolist()

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

Submission status: Runtime Error

Solution code:
n,q=map(int, input().split())  #複数数値入力　「A B」みたいなスペース空いた入力のとき
ab=[list(map(int,list(input()))) for i in range(n)]
px=[list(map(int,list(input()))) for i in range(q)]
#print(ab)
#print(px)
ans= [[0 for i in range(n)] for i in range(n)]
ans2= [0 for i in range(n)]
for i in range(n):
    ans[i][i] = 1
for i in range(len(ab)):
    ans[ab[i][0]-1][ab[i][1]-1]+=1
for i in range(n):
    for j in range(i+1,n):
        if(ans[i][j]>0):
            for k in range(j,n):
                ans[i][k]+=ans[j][k]
for i in range(q):
    for j in range(n):
        ans2[j]+=px[i][1]* 1 if ans[px[i][0]-1][j] else 0
print(ans2)

Submission status: Runtime Error

Solution code:
N,M = map(int,input().split())
a = [tuple(map(int, input().split())) for _ in range(N-1)]
b = [list(map(int, input().split())) for _ in range(M)]
ans=[0]*N
results = {}
for word in a:
    results.setdefault(word[0], []).append(word[1])

# neを根とする部分木にxを足す
def hukasa(ne,x):
    global ans
    global results
    ans[ne -1] += x
    if ne in results:
        for i in results[ne]:
            hukasa(i,x)


for i in b:
    hukasa(i[0],i[1])

for i in ans:
    print(i, end=" ")