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: Wrong Answer

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

c = [0 for i in range(n)]
parent_of = [0 for i in range(n)]

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

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

for i in range(1, n):
    c[i] += c[parent_of[i]]

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

Submission status: Wrong Answer

Solution code:
import sys
import queue
#+++++
		
def main():
	n,q = map(int, input().split())
	tree=[[] for _ in range(n+1)]
	hh=[0 for _ in range(n+1)]
	ret=[0 for _ in range(n+1)]
	
	for i in range(n-1):
		pa,ch = map(int, input().split())
		tree[pa].append(ch)
		
	for v in range(q):
		nd, hv = map(int, input().split())
		hh[nd] += hv
		
	ol = queue.Queue(2*n+1)
	ret[1]=hh[1]
	vv=hh[1]
	for cc in tree[1]:
		ol.put((vv,cc))
		
	while not ol.empty():
		ph,nd=ol.get()
		ret[nd]=hh[nd]+ph
		vv=ret[nd]
		for cc in tree[nd]:
			ol.put((vv,cc))

	rets=' '.join([str(v) for v in ret[1:]])
	print(rets)
	
	
#+++++

if __name__ == "__main__":
	if sys.platform =='ios':
		sys.stdin=open('inputFile.txt')
	else:
		pass
		input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Wrong Answer

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools, os, pdb
sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def _I(): return int(sys.stdin.readline())
def _F(): return float(sys.stdin.readline())
def _pf(s): return print(s, flush=True)
def perr(s): return print(s, file=sys.stderr)

if 'LOCAL' in os.environ:
    N = 2* 10** 5
    Q = 2 * 10 ** 5
    AB = [[i, i + 1] for i in range(1, N)]
    PX = [[i, 10] for i in range(Q)]
else:
    N, Q = LI()
    AB = []
    PX = []
    for i in range(N-1):
        AB.append(LI())

    for i in range(Q):
        PX.append(LI())


"""
そもそも各頂点の部分木をdictに入れましょうか？
参照するような形で。
2には3
3には4,5
4,5はNoneだと、参照しやすいか？

カウントを若い順にやっていく
"""
AB = sorted(AB, key=lambda x: x[0])
perr('AB')
perr(AB)
d = {}
for p, x in PX:
    if p not in d.keys():
        d[p] = 0
    d[p] += x
for a, b in AB:
    if b not in d.keys():
        d[b] = 0
    if a not in d.keys():
        d[a] = 0
    d[b] += d[a]
for i in range(1, N+1):
    print(d[i], end=' ')

Submission status: Wrong Answer

Solution code:
n , q = map(int, input().split())
 
tree = {}
for i in range(n-1):
    a, b = map(int, input().split())
    if a in tree:
        tree[a].append(b)
    else:
        tree[a] = [b]
 
op = [0] * (n+1)
for i in range(q):
    p, x = map(int, input().split())
    op[p] += x
 
for root, reaf in tree.items():
    for i in reaf:
        op[i] += op[root]
 
print(*op[1:])

Submission status: Wrong Answer

Solution code:
import sys
from collections import Counter
from collections import defaultdict
sys.setrecursionlimit(10**8)
input = lambda: sys.stdin.readline()[:-1]
cnt=Counter()
data=defaultdict(set)

n,q=map(int,input().split())
ab=[tuple(map(int,input().split())) for i in range(n-1)]
px=[tuple(map(int,input().split())) for i in range(q)]
ab.sort(key=lambda tup:(tup[0],tup[1]))
for i in ab:
	data[i[0]].add(i[1])
for j in px:
	cnt[j[0]]+=j[1]

def plus(now,value):
	for i in data[now]:
		cnt[i]+=value
		plus(i,cnt[i])
		
plus(1,cnt[1])

ans=list(cnt.items())
ans.sort(key=lambda tup:tup[0])
ans =[str(i[1]) for i in ans]
print(' '.join(ans))

Submission status: Wrong Answer

Solution code:
def flatten(data):
    return [element
            for item in data
            for element in (flatten(item) if hasattr(item, '__iter__') else [item])]
N,Q = map(int,input().split())
AB=[]
PQ=[]
for n in range(N-1):
    AB.append(list(map(int,input().split())))
for q in range(Q):
    PQ.append(list(map(int,input().split())))
X = [0]*N
for pq in PQ:
    X[pq[0]-1] += pq[1]
    next=[a[1] for a in AB if a[0]-1==pq[0]-1]
    while next!=[]:
        next2=[]
        for n in next:
            X[n-1] += pq[1]
            next2.append([a[1] for a in AB if a[0]-1==n-1])
        next=flatten(next2)

print(*X)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(1000000) 
 
N,M = map(int,input().split())
a = [list(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])
 
for i in b:
    ans[i[0]-1] += i[1]
 
def sumup(ne):
    global ans
    if ne in results:    
        for k in results[ne]:
            ans[k-1] += ans[ne-1]
            sumup(k)
 
sumup(1)
for i in ans:
    print(i)

Submission status: Wrong Answer

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

for i in range(n)[::-1]:
  if calc_tree[i] == []:
    
    tmp = [i+1]
  
    for j in range(n-1)[::-1]:
      if tree[j][1] in tmp:
        tmp.append(tree[j][0])
    calc_tree[i] = tmp
    for j in range(1,len(tmp)):
      if calc_tree[j] == []:
        for k in range(j,len(tmp)):
          calc_tree[tmp[j]-1].append(tmp[k])

    calc_tree[i] = (tmp)

ans = [0] * n

for i in range(q):
  ans[px[i][0]-1] += px[i][1]

for i in range(n):
  temp = 0
  for j in calc_tree[i]:
    temp += ans[j-1]
  print(temp)

Submission status: Wrong Answer

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

c = [0 for i in range(n)]
parent_of = [0 for i in range(n)]

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

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

for i in range(1, n):
    c[i] += c[parent_of[i]]

print(c)

Submission status: Wrong Answer

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]

n,q = map(int, input().split())
#長さn個のリストを入れ子にしたリストの作成：adj
adj = [[] for i in range(n)]

#adjに繋がっている要素を上流下流関わらず全て加える。
for j in range(n-1):
    a,b=map(int, input().split())
    adj[a-1].append(b-1)
    adj[b-1].append(a-1) 

#加算する値を合計したリストの作成
queries = [0 for i in range(n)]
for j in range(q):
    p, x = map(int, input().split())
    queries[p-1] += x

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

#aの値，直前の値，直前のaの値
st = [(0, 0, -1)] 

#つながってる奴の一番後ろから処理していく。
#０スタート→1,2繋がってるなら2にいく。2に3が繋がってるなら次は3。
#3に繋がってるのがなければ1に戻る。
#この際，aの直前の値をタプルで保持したままリストに挿入して保管しておく。
while st:
    #stの先頭を取り出す。初期値は末尾のため-1
    l = st.pop()  
    print(l)
    ans[l[0]] = l[1] + queries[l[0]]
    for v in adj[l[0]]:
        if v != l[2]:
            st.append((v, ans[l[0]], l[0]))

print(*ans)

Submission status: Wrong Answer

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]

n,q = map(int, input().split())
#長さn個のリストを入れ子にしたリストの作成：adj
adj = [[] for i in range(n)]

#adjに繋がっている要素を上流下流関わらず全て加える。
for j in range(n-1):
    a,b=map(int, input().split())
    adj[a-1].append(b-1)
    adj[b-1].append(a-1)
print(adj) 

#加算する値を合計したリストの作成
queries = [0 for i in range(n)]
for j in range(q):
    p, x = map(int, input().split())
    queries[p-1] += x
print(queries)

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

#aの値，直前の値，直前のaの値
st = [(0, 0, -1)] 

print('answer roop')

#つながってる奴の一番後ろから処理していく。
#０スタート→1,2繋がってるなら2にいく。2に3が繋がってるなら次は3。
#3に繋がってるのがなければ1に戻る。
#この際，aの直前の値をタプルで保持したままリストに挿入して保管しておく。
while st:
    #stの先頭を取り出す。初期値は末尾のため-1
    l = st.pop()  
    print(l)
    ans[l[0]] = l[1] + queries[l[0]]
    for v in adj[l[0]]:
        if v != l[2]:
            st.append((v, ans[l[0]], l[0]))

print(*ans)

Submission status: Wrong Answer

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

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

#入力

stack = [0]
append = stack.append
while len(stack) > 0:
    now = stack.pop()
    for i in tree[now]:
        ans[i] += ans[now]
        append(i)

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

Submission status: Wrong Answer

Solution code:
n,q = list(map(int, input().split()))
#長さn個のリストを入れ子にしたリストの作成：adj
adj = [[] for i in range(n)]

#adjに繋がっている要素を上流下流関わらず全て加える。
for j in range(n-1):
    a,b=list(map(int, input().split()))
    adj[a-1].append(b-1)
    adj[b-1].append(a-1)
print(adj) 

#加算する値を合計したリストの作成
queries = [0 for i in range(n)]
for j in range(q):
    p, x = list(map(int, input().split()))
    queries[p-1] += x
print(queries)

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

st = [(0, 0, -1)] #なんのため

print('answer roop')

#つながってる奴の一番後ろから処理していく。
#０スタート→1,2繋がってるなら2にいく。2に3が繋がってるなら次は3。
#3に繋がってるのがなければ1に戻る。
#この際，aの直前の値をタプルで保持したままリストに挿入して保管しておく。
while st:
    l = st.pop()  #stの先頭を取り出す。初期値は末尾のため-1
    print(l)
    ans[l[0]] = l[1] + queries[l[0]]
    for v in adj[l[0]]:
        if v != l[2]:
            st.append((v, ans[l[0]], l[0]))

print(*ans)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(300000)
input = sys.stdin.readline

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

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

Co = [0] * (N + 1)
import collections

q = collections.deque([(1, 0)])
while (len(q) > 0):
    now, pa = q.popleft()
    Co[now] = Ps[now] + Co[pa]
    for c in children[now]:
        q.append((c, now))

Co.pop(0)
print(" ".join(map(str, Co)))

Submission status: Wrong Answer

Solution code:
#inprove the spped of input
import sys
input = sys.stdin.readline

#入力n,q,の受け取り
n,q = map(int, input().split())

#ab[i]には頂点iにつながる頂点たちが列挙されている
#ただし、最後の数字は各頂点以下に加えるxの値
ab = [0]*n
for i in range(n):
    ab[i] = []
for i in range(n-1):
    inp = list(map(int, input().split()))
    inp.sort()
    ab[inp[0]-1].append(inp[1])
for i in range(n):
    ab[i].append(0)

#入力p,xの受け取り
for i in range(q):
    px = list(map(int, input().split()))
    ab[px[0]-1][-1] += px[1]

#あとは答えを出して行って終わり
for i in range(n):
    len_ = len(ab[i])-1
    for j in range(len_):
        ab[ ab[i][j]-1 ][-1] += ab[i][-1]
ans = [0]*n
for i in range(n):
    ans[i] = str(ab[i][-1])
print(" ".join(ans))

Submission status: Wrong Answer

Solution code:
n, q = [int(x) for x in input().split()]
vs   = []
xs   = []
	
for _ in range(0, n + 1):
	vs.append([])
	xs.append(0)

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

for _ in range(0, q):
	p, x   = [int(x) for x in input().split()]
	xs[p] += x
	
for i in range(1, n + 1):
	x = xs[i]
	for v in vs[i]:
		xs[v] += x	

print(" ".join(str(x) for x in xs[1:]))

Submission status: Wrong Answer

Solution code:
n, q = list(map(int, input().split()))
graph = [[] for _ in range(n+1)]
for _ in range(n-1):
    ai, bi = list(map(int, input().split()))
    graph[ai].append(bi)
    graph[bi].append(ai)
    
parent = [[] for _ in range(n+1)]
child = [[] for _ in range(n+1)]
current = 1
while current <= n:
    for j in graph[current]:
        if current in child[j]:
            continue
        child[current].append(j)
    current += 1
#print(child)
tpoint = [0]*(n+1)
for i in range(q):
    pi, xi = list(map(int, input().split()))
    tpoint[pi] += xi

for i in range(1, n+1):
    for j in child[i]:
        tpoint[j] += tpoint[i]
print(*tpoint[1:], sep='\n')

Submission status: Wrong Answer

Solution code:

from collections import deque

N, Q = [int(i) for i in input().split()]
edges = [[] for _ in range(N + 1)]
result = [0] * (N + 1)

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

q = deque()
q.append(1)

while 0 < len(q):
    v = q.pop()
    x = result[v]
    
    for c in edges[v]:
        result[c] += x
        q.append(c)

for r in result[1:N]:
    print("%d " % r, end="")

print(result[N])

Submission status: Wrong Answer

Solution code:
n, q = map(int, input().split())
ki = [0]*(n+1)
for i in range(n-1):
  a, b = map(int, input().split())
  ki[b] = a
#このノードはどの頂点に紐づいているか

c = [0]*(n+1)
for i in range(q):
  p, x = map(int, input().split())
  c[p] += x
#まず、スタート地点になるノードを加算する（初期値）

 
for i in range(1, n+1):
  c[i] += c[ki[i]]
#前の頂点を最終形にして、初期値含めて加算された値を全て子ノードに足す。若い順からやってく。
 
print(" ".join(map(str, c[1:])))
#頂点0以外を出力

Submission status: Wrong Answer

Solution code:
n, q = map(int, input().split())
ki = [0]*(n+1)
for i in range(n-1):
  a, b = map(int, input().split())
  ki[b] = a
#このノードはどの頂点に紐づいているか

c = [0]*(n+1)
for i in range(q):
  p, x = map(int, input().split())
  c[p] += x
#まず、スタート地点になるノードを加算する（初期値）

 
for i in range(1, n+1):
  c[i] += c[ki[i]]
  print(c)
#前の頂点を最終形にして、初期値含めて加算された値を全て子ノードに足す。若い順からやってく。
 
print(" ".join(map(str, c[1:])))
#頂点0以外を出力

Submission status: Wrong Answer

Solution code:

N, Q = map(int, input().split())
A = []
B = []

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

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


T = {}
for i in range(len(A)):
    a = A[i]
    b = B[i]
    if a in T:
        T[a].append(b)
    else:
        T[a] = [b]

d = [0] * N

for i in range(len(P)):
    p = P[i]
    x = X[i]
    d[p - 1] += x

for i in range(N):
    if i + 1 in T:
        for p in T[i + 1]:
            d[p - 1] += d[i]

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

Submission status: Wrong Answer

Solution code:
import sys
import queue
input = sys.stdin.readline
N, Q = map(int, input().split())

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

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


q = [1]
while q:
    now = q.pop()
    for next in tree[now]:
            values[next] += values[now]
            q.append(next)

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

Submission status: Wrong Answer

Solution code:

from collections import deque

N, Q = [int(i) for i in input().split()]
edges = [[] for _ in range(N + 1)]
result = [0] * (N + 1)

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

q = deque()
q.append(1)

while 0 < len(q):
    v = q.pop()
    x = result[v]
    
    for c in edges[v]:
        result[c] += x
        q.append(c)

for r in result[1:N+1]:
    print("%d " % r, end="")

Submission status: Wrong Answer

Solution code:
import sys
from math import factorial, ceil, floor
from bisect import bisect_right as bsr
from operator import itemgetter as ig
from collections import defaultdict as dd
from collections import deque

# お約束
args = None
INF = float("inf")
MOD = int(1e9 + 7)
def int1(n):
    return int(n) - 1
def input():
    return next(args)
def parse(*params):
    if len(params) == 1:
        return params[0](next(args))
    return tuple(p(v) for p, v in zip(params, next(args).split()))
def debug(*v):
    if __debug__:
        print(*v, file=sys.stderr)

# エントリーポイント
def main():
    N, Q = parse(int, int)
    edges = [[] for _ in range(N)]
    for _ in range(N - 1):
        a, b = parse(int1, int1)
        edges[a] += [b]
    vals = [0] * N
    for _ in range(Q):
        p, x = parse(int1, int)
        vals[p] += x

    counter = [0] * N
    que = [(0, 0)]
    alr = [False] * N
    while que:
        v, x = que.pop()
        alr[v] = True
        counter[v] += x + vals[v]
        for n in edges[v]:
            if not alr[n]:
                que.append((n, counter[v]))

    for v in counter:
        print(v)

if __name__ == '__main__':
    args = iter(sys.stdin.read().split("\n"))
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque

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

graph, parents, values, visited = [],[],[],[]
for _ in range(N):
  graph.append([])
  parents.append(-1)
  values.append(0)
  visited.append(False)

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

bfs_queue = deque()
bfs_queue.append(0)
bfs_queue_len = 1
while bfs_queue_len:
  cur = bfs_queue.popleft()
  bfs_queue_len -= 1
  visited[cur] = True

  for other in graph[cur]:
    if not visited[other]:
      parents[other] = cur
      bfs_queue_len += 1
      bfs_queue.append(other)

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

for i in range(N):
  if i != 0:
    values[i] += values[parents[i]]
  print(values[i],end=" ")

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(1000000)
 
 
n,q=map(int,input().split())
ki=[[] for i in range(n+1)]
ki[0]="null"
 
for i in range(n-1):
    a,b=map(int,input().split())
    ki[a].append(b)
 
scores=[0 for i in range(n+1)]
scores[0]="null"
for i in range(q):
    p,x=map(int,input().split())
    scores[p]+=x
 
 
ans=[0 for i in range(n+1)]
ans[0]="null"
point=0
 
 
def tansa(n,point):
    point+=scores[n]
    for p in ki[n]:
        tansa(p,point)
    else:
        ans[n]=point
        
tansa(1,0)
 
ans=ans[1:]
ans=[str(i) for i in ans]
print(" ".join(ans))

Submission status: Wrong Answer

Solution code:

from collections import deque

N, Q = [int(i) for i in input().split()]
edges = [[] for _ in range(N + 1)]
result = [0] * (N + 1)

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

q = deque()
q.append(1)

while 0 < len(q):
    v = q.pop()
    x = result[v]
    
    for c in edges[v]:
        result[c] += x
        q.append(c)

print(result[1:(N+1)])

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(1000000)


n,q=map(int,input().split())
ki=[[] for i in range(n+1)]
ki[0]="null"
 
for i in range(n-1):
    a,b=map(int,input().split())
    ki[a].append(b)
 
scores=[0 for i in range(n+1)]
scores[0]="null"
for i in range(q):
    p,x=map(int,input().split())
    scores[p]+=x
 
 
ans=[0 for i in range(n+1)]
ans[0]="null"
point=0
 
 
def tansa(n,point):
    point+=scores[n]
    for p in ki[n]:
        tansa(p,point)
    else:
        ans[n]=point
        
tansa(1,0)
 
ans=ans[1:]
ans=[str(i) for i in ans]
print(" ".join(ans))

Submission status: Wrong Answer

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

def make_trees(n, A, B):
    global trees
    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):
    if node:
        node.val += x
        for i in node.vertex:
            dfs(trees[i], node.val)


def sol(n, q, A, B, P, X):
    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
        t.val += x
    # accmulative run
    dfs(trees[0], 0)
    #
    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: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(200010)

def main():
    input = sys.stdin.readline
    N, Q = map(int,input().split())
    G = [[] for k in range(N+1)]
    for k in range(N-1):
        a, b = map(int,input().split())
        G[a].append(b)
    kyori = [0 for k in range(N+1)]
    for k in range(Q):
        p, x = map(int,input().split())
        kyori[p] -= x
    def dfs(now, dist):
        for tsugi in G[now]:
            if kyori[tsugi] <= 0:
                kyori[tsugi] = -kyori[tsugi]
                kyori[tsugi] += dist
                dfs(tsugi, kyori[tsugi])
    kyori[1] = -kyori[1]
    dfs(1,kyori[1])
    print(*kyori[1:], sep = " ")

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline
sys.setrecursionlimit(1000000)

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)


c=[0]*(n+1)


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

def dfs(i):
    for j in g[i]:
        c[j]+=c[i]
        dfs(j)

dfs(1)


print(*c[1:])

Submission status: Wrong Answer

Solution code:
a,b=map(int,input().split())
c=[list(map(int,input().split())) for i in range(a-1)]
c.sort()
d=[list(map(int,input().split())) for i in range(b)]

ans=[0 for i in range(a)]
for i in d:
  ans[i[0]-1]+=i[1]
  
for i in c:
  ans[i[1]-1]+=ans[i[0]-1]
  
print(" ".join(map(str,ans)))

Submission status: Wrong Answer

Solution code:
n,q=map(int,input().split())
l=sorted([list(map(int,input().split())) for _ in range(n-1)])
ans=[0]*n
for i in range(q):
	a,b=map(int,input().split())
	ans[a-1]+=b
for i in l:
	ans[i[1]-1]+=ans[i[0]-1]
print(*ans)

Submission status: Wrong Answer

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

#print(n,q)
edge = []
for i in range(n-1):
    a = list(map(int, input().split()))
    edge.append(a)

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

#print(edge,add_list)

ans = [0] * n
edge_list = [-1] * n

for e in edge:
    edge_list[e[1]-1] = e[0]-1

add_value = [0]*n
for v in add_list:
    add_value[v[0]-1] += v[1]

#print(edge_list)
#print(add_value)


dp = [-1] * n


def get_value(i):
    if(dp[i] != -1):
        return dp[i]
    tmp = add_value[i]
    if edge_list[i] != -1:
        tmp += get_value(edge_list[i])
    dp[i] = tmp
    return dp[i]


for i in range(n):
    ans[i] = get_value(i)
    #print(i,ans)

print(*ans)

Submission status: Wrong Answer

Solution code:
import sys
from math import factorial, ceil, floor
from bisect import bisect_right as bsr
from operator import itemgetter as ig
from collections import defaultdict as dd

# お約束
args = None
INF = float("inf")
MOD = int(1e9 + 7)
def int1(n):
    return int(n) - 1
def input():
    return next(args)
def parse(*params):
    if len(params) == 1:
        return params[0](next(args))
    return tuple(p(v) for p, v in zip(params, next(args).split()))
def debug(*v):
    if __debug__:
        print(*v, file=sys.stderr)

# エントリーポイント
def main():
    N, Q = parse(int, int)
    edges = [[] for _ in range(N)]
    for _ in range(N - 1):
        a, b = parse(int1, int1)
        edges[a] += [b]
    vals = [0] * N
    for _ in range(Q):
        p, x = parse(int1, int)
        vals[p] += x

    sum_vals = [0] * N
    que = [(0, 0)]
    while que:
        v, x = que.pop()
        sum_vals[v] += x + vals[v]
        for n in edges[v]:
            que.append((n, sum_vals[v]))

    for v in sum_vals:
        print(v)

if __name__ == '__main__':
    args = iter(sys.stdin.read().split("\n"))
    main()

Submission status: Wrong Answer

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)]
args=[0]*(N+1)

for j in range(Q):
  args[px[j][0]]+=px[j][1]
for k in range(N-1):
  args[ab[k][1]]+=args[ab[k][0]]
args.pop(0)
print(*args)

Submission status: Wrong Answer

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

graph, parents, values = [],[],[]
for _ in range(N):
  graph.append([])
  parents.append(-1)
  values.append(0)

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

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

for i in range(N):
  if i != 0:
    values[i] += values[parents[i]]
  print(values[i],end=" ")

Submission status: Wrong Answer

Solution code:
import sys

stdin = sys.stdin
na = lambda: map(int, stdin.readline().split())

def main():
  N, Q = na()

  ab = []
  for _ in range(N-1):
    a, b = na()
    ab.append([a, b])
  ab.sort()

  counter = [0] * (N+1)
  for _ in range(Q):
    p, x = na()
    counter[p] += x
  for i in range(N - 1):
    counter[ab[i][1]] += counter[ab[i][0]]
  print(*counter[1:])

if __name__ == "__main__":
  main()

Submission status: Wrong Answer

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

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

children = [[] for i in range(n+1)]
for i in range(1,n+1):
    c = data[i]
    pos = 0
    while pos < len(c):
        c += data[c[pos]]
        pos += 1
    children[i] = c

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

score = [0]*(n+1)
for i, c in enumerate(children):
    score[i] += score_[i]
    for j in c:
        score[j] += score_[i]

scorelist = []
for i in range(1,n+1):
    s = str(score[i])
    scorelist.append(s)
print(' '.join(scorelist))

Submission status: Wrong Answer

Solution code:
N, Q = map(int, input().split(" "))
 
ns= [list(map(int, input().split(" ")))  for _ in range(N-1)]
 
flags = [True]+[False]*(N-1)
dic = [[] for _ in range(N)]
rlt = [0]*N
 
for i in range(N-1):
  dic[ns[i][1]-1] += [ns[i][0]-1]
  dic[ns[i][0]-1] += [ns[i][1]-1]
  
for p, x in (map(int, input().split()) for _ in range(Q)):
    rlt[p - 1] += x
  
for k in range(N):
  for l in dic[k]:
    if flags[l]:
      continue
    else:
      rlt[l] += rlt[k]
      flags[l] = True
    
print(" ".join(map(str, rlt)))

Submission status: Wrong Answer

Solution code:
N, Q = map(int, input().split(" "))
 
ns= [list(map(int, input().split(" ")))  for _ in range(N-1)]
vs = [list(map(int, input().split(" ")))  for _ in range(Q)]
 
flags = [False]*N
dic = [[] for _ in range(N)]
rlt = [0]*N
 
for i in range(N-1):
  dic[ns[i][1]-1] += [ns[i][0]-1]
  dic[ns[i][0]-1] += [ns[i][1]-1]
  
for j in range(Q):
  rlt[vs[j][0]-1] += vs[j][1]
  
for k in range(N):
  flags[k] = True
  for l in dic[k]:
    if flags[l]:
      continue
    else:
      rlt[l] += rlt[k]
      flags[l] = True
    
print(" ".join(map(str, rlt)))

Submission status: Wrong Answer

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):
    yy=y[k][0]-1
    zz=y[k][1]-1
    ans[zz]=ans[zz]+ans[yy]
print(*ans,sep=" ")

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

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

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

score = defaultdict(int)
for i in range(q):
    p, x = list(map(int,input().split()))
    score[p] += x
    target = data[p]
    pos = 0
    while pos < len(target):
        target += data[target[pos]]
        pos += 1
    for t in target:
        score[t] += x

scorelist = []
for i in range(n):
    s = str(score[i+1])
    scorelist.append(s)
print(' '.join(scorelist))

Submission status: Wrong Answer

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

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

comp = [[] for i in range(n+1)]
for i in range(1,n+1):
    c = data[i]
    pos = 0
    while pos < len(c):
        c += data[c[pos]]
        pos += 1
    comp[i] = c

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

scorelist = []
for i in range(1,n+1):
    s = str(score[i])
    scorelist.append(s)
print(' '.join(scorelist))

Submission status: Wrong Answer

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