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: Accepted

Solution code:

NQ = input().split(' ')
N = int(NQ[0])
Q = int(NQ[1])
out_put_list = [0] * N
tree_list = {}
for i in range(N):
    tree_list[i] = []

for i in range(N-1):
    ab = input().split(' ')
    a = int(ab[0]) -1
    b = int(ab[1]) -1
    tree_list[a].append(b)

for _ in range(Q):
    px = input().split(' ')
    p = int(px[0])
    x = int(px[1])
    out_put_list[p-1] += x

for i in range(len(tree_list)):
    for num in tree_list[i]:
        out_put_list[num] += out_put_list[i]

print(*out_put_list)

Submission status: Accepted

Solution code:
N, Q = [int(v) for v in input().split()]

class Node:
    def __init__(self):
        self.list = []
        self.score = 0

    def add(self, node):
        self.list.append(node)

nodes = []
score = [0] * N

for i in range(0, N):
    nodes.append([])

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

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

l = [0]

i = 0
while i < len(l):
    node = l[i]
    for child in nodes[node]:
        score[child] += score[l[i]]
        l.append(child)
    i += 1

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

Submission status: Accepted

Solution code:
class Node:
    def __init__(self, index):
        self.count = 0
        self.fr = -1
        self.index = index


N, Q = map(int, input().split())
node = [Node(i) for i in range(N)]
for i in range(N - 1):
    fr, to = map(int, input().split())
    node[to - 1].fr = fr - 1

for i in range(Q):
    fr, c = map(int, input().split())
    node[fr - 1].count += c

print(node[0].count, end=' ')

for i in range(1, N):
    node[i].count += node[node[i].fr].count
    if not i == N:
        print(node[i].count, end=' ')
    else:
        print(node[i].count)

Submission status: Accepted

Solution code:
def solve(edges,values):
    stack = [1]
    visited = set()
    while stack:
        curr = stack.pop()
        if curr not in visited:
            visited.add(curr)
            for kid in edges[curr]:
                if kid not in visited:
                    values[kid-1] += values[curr-1]
                    stack.append(kid)

    for i in values:
        print(i,end = ' ')

def main():
    n,q = map(int,input().split())
    edges = {}
    for i in range(1,n+1):
        edges[i] = []

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

    values = [0]*n

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

    solve(edges,values)


main()

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
n,q=map(int,input().split())
l=[list(map(int,input().split())) for i in range(n-1)]
l2=[list(map(int,input().split())) for i in range(q)]
connection=[[] for i in range(n)]
for i in range(n-1):
  connection[l[i][0]-1].append(l[i][1]-1)
L4=[0 for i in range(n)]
for i in range(q):
  L4[l2[i][0]-1]+=l2[i][1]
distance=[0 for i in range(n)]
distance[0]=L4[0]

L=[0]
L2=[]
L3=[]
while len(L2)!=n and len(L)!=0:
  for j in range(len(L)):
    for k in range(len(connection[L[j]])):
      distance[connection[L[j]][k]]=distance[L[j]]+L4[connection[L[j]][k]]
      L3.append(connection[L[j]][k])
    L2.append(L[j])
  L=L3
  L3=[]
for i in range(len(distance)):
  print(distance[i])

Submission status: Accepted

Solution code:
N,Q = map(int, input().strip().split(' '))
tree_dict = { i:set() for i in range(N)}
for _ in range(N-1):
  a,b = map(int, input().strip().split(' '))
  a,b = a-1, b-1
  tree_dict[a].add(b)
  tree_dict[b].add(a)
tree_counter = [0 for _ in range(N)]
for _ in range(Q):
  p,x = map(int, input().strip().split(' '))
  tree_counter[p-1] += x

stack = []
for c in tree_dict[0]:
  tree_counter[c] += tree_counter[0]
  stack.append((0, c))

for i in range(N-1):
  parent,child = stack.pop()
  for c in tree_dict[child]-{parent}:
    tree_counter[c] += tree_counter[child]
    stack.append((child, c))
  
print(*tree_counter)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
n,q=map(int,input().split())
l=[list(map(int,input().split())) for i in range(n-1)]
l2=[list(map(int,input().split())) for i in range(q)]
connection=[[] for i in range(n)]
for i in range(n-1):
  connection[l[i][0]-1].append(l[i][1]-1)
L4=[0 for i in range(n)]
for i in range(q):
  L4[l2[i][0]-1]+=l2[i][1]
distance=[0 for i in range(n)]
distance[0]=L4[0]

L=[0]
L2=[]
L3=[]
while len(L2)!=n and len(L)!=0:
  for j in range(len(L)):
    for k in range(len(connection[L[j]])):
      distance[connection[L[j]][k]]=distance[L[j]]+L4[connection[L[j]][k]]
      L3.append(connection[L[j]][k])
    L2.append(L[j])
  L=L3
  L3=[]
for i in range(len(distance)):
  distance[i]=str(distance[i])
print(' '.join(distance))

Submission status: Accepted

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)]

dic = [[] for _ in range(N)]
rlt = [0]*N


for i in range(N-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):
  for l in dic[k]:
    rlt[l] += rlt[k]
    
print(" ".join(map(str, rlt)))

Submission status: Accepted

Solution code:
n,q = map(int,input().split())
ki = [[] for i in range(n+1)] 
c = [0] * (n+1)

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

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

st = [1]
while st:
    tmp = st.pop()
    for i in ki[tmp]:
        c[i] += c[tmp]
    st += ki[tmp]

print(*c[1:])

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline


class Node:
    def __init__(self, parent_id=None):
        self.val = 0
        self.parent_id = parent_id


n, q = map(int, input().split())
tree = [Node() for _ in range(n)]

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

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

for i in range(1, n):
    tree[i].val += tree[tree[i].parent_id].val

print(*[node.val for node in tree])

Submission status: Accepted

Solution code:
from collections import deque


def solve(n, q, a, b, p, x):
    counter = [0] * n
    q_sum = [0] * n
    for i in range(q):
        q_sum[p[i]] += x[i]
    # pprint(q_sum)

    edges = {}
    for i in range(n-1):
        if a[i] not in edges:
            edges[a[i]] = []
        edges[a[i]].append(b[i])
    # pprint(edges)

    counter[0] = q_sum[0]
    children = deque()
    for child in edges[0]:
        counter[child] = q_sum[0]
        children.append(child)
    while children:
        child = children.popleft()
        counter[child] += q_sum[child]
        # print("child")
        # print(child, counter[child])
        if child in edges:
            for c in edges[child]:
                counter[c] = counter[child]
                # print("c")
                # print(c, counter[c])
                children.append(c)

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

if __name__ == "__main__":
    n, q = list(map(int, input().strip().split(" ")))
    a = []
    b = []
    for _ in range(n-1):
        a_i, b_i = list(map(int, input().strip().split(" ")))
        a.append(a_i - 1)
        b.append(b_i - 1)

    p = []
    x = []
    for _ in range(q):
        p_i, x_i = list(map(int, input().strip().split(" ")))
        p.append(p_i-1)
        x.append(x_i)
    solve(n, q, a, b, p, x)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
n,q=map(int,input().split())
l=[]
for i in range(n-1):
  l.append(list(map(int,input().split())))
l2=[]
for i in range(q):
  l2.append(list(map(int,input().split())))
connection=[]
for i in range(n):
  connection.append([])
for i in range(n-1):
  connection[l[i][0]-1].append(l[i][1]-1)
 
L4=[]
for i in range(n):
  L4.append(0)
for i in range(q):
  L4[l2[i][0]-1]+=l2[i][1]
distance=[]
for i in range(n):
  distance.append(0)
distance[0]=L4[0]

L=[0]
L2=[]
L3=[]
while len(L2)!=n and len(L)!=0:
  for j in range(len(L)):
    for k in range(len(connection[L[j]])):
      distance[connection[L[j]][k]]=distance[L[j]]+L4[connection[L[j]][k]]
      L3.append(connection[L[j]][k])
    L2.append(L[j])
  L=L3
  L3=[]
for i in range(len(distance)):
  distance[i]=str(distance[i])
print(' '.join(distance))

Submission status: Accepted

Solution code:
from operator import itemgetter
n,q=map(int,input().split())
a=[]
s=[0]


for i in range(n-1):
    a.append([int(j) for j in input().split()])
    s.append(0)

a.sort(key=itemgetter(0))

for i in range(0,q):
    P,X=map(int,input().split())
    s[P-1]=s[P-1]+X


for j in range(0,n-1):
    s[a[j][1]-1]=s[a[j][1]-1]+s[a[j][0]-1]


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

Submission status: Accepted

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

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

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

print( *ans )

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
n,q=map(int,input().split())
l=[]
for i in range(n-1):
  l.append(list(map(int,input().split())))
l2=[]
for i in range(q):
  l2.append(list(map(int,input().split())))
connection=[]
for i in range(n):
  connection.append([])
for i in range(n-1):
  connection[l[i][0]-1].append(l[i][1]-1)
 
L4=[]
for i in range(n):
  L4.append(0)
for i in range(q):
  L4[l2[i][0]-1]+=l2[i][1]
distance=[0 for i in range(n)]
distance[0]=L4[0]
ans=[0 for i in range(n)]
ans[0]=L4[0]
L=[0]
L2=[]
L3=[]
while len(L2)!=n and len(L)!=0:
  for j in range(len(L)):
    for k in range(len(connection[L[j]])):
      distance[connection[L[j]][k]]=distance[L[j]]+L4[connection[L[j]][k]]
      L3.append(connection[L[j]][k])
    L2.append(L[j])
  L=L3
  L3=[]
for i in range(len(distance)):
  distance[i]=str(distance[i])
print(' '.join(distance))

Submission status: Accepted

Solution code:
from collections import deque
n, q = map(int,input().split())
d = [[] for i in range(n)]
for i in range(n-1):
    ai, bi = map(int,input().split())
    d[ai-1].append(bi-1)
    d[bi-1].append(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)]
s = deque()
s.append(0)
visited = [False for i in range(n)]
while len(s) > 0:
    x = s.popleft()
    visited[x] = True
    sp[x] += px[x]
    for xc in d[x]:
        if not visited[xc]:
            s.append(xc)
            sp[xc] += sp[x]
for i in range(n):
    print(sp[i])

Submission status: Accepted

Solution code:
import sys
from operator import itemgetter

n,q = [ int(x) for x in sys.stdin.readline().strip().split() ]
edge= [ [] for _ in range(n-1) ]
for i in range(n-1):
    edge[i] = [ int(x)-1 for x in sys.stdin.readline().strip().split() ]
edge.sort( key=itemgetter(0) )
c= [ 0 for _ in range(n) ]
for i in range(q):
    p,x= [ int(x) for x in sys.stdin.readline().strip().split() ]
    c[p-1]+= x
#
for a,b in edge: c[b]+= c[a]

print( *c )

Submission status: Accepted

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

children_map = [None] * n
vals = [0] * n

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

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

for i in range(n):
    parent = children_map[i]
    if parent is not None:
        vals[i] += vals[parent]

print(*vals)

Submission status: Accepted

Solution code:
from sys import stdin
n, q = map(int, input().split())
cnt = [0]*n
root = [[] for i in range(n)]

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

for i in range(q):
    p, x = map(int, stdin.readline().split())
    cnt[p-1] += x

tmparr = [0]
while tmparr:
    tmpi = tmparr.pop()
    for i in root[tmpi]:
        cnt[i] += cnt[tmpi]
    tmparr += root[tmpi]
print(*cnt)

Submission status: Accepted

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

for i in range(2,n+1):
    c[i] += c[ki[i]]
print(*c[1:])

Submission status: Accepted

Solution code:
import sys

n, q = map(int, sys.stdin.readline().split())

near = [[] for _ in range(n+1)]
solved = [0] * (n+1)

child = [[] for _ in range(n+1)]
for i in range(n-1):
    a, b = map(int, sys.stdin.readline().split())
    near[a].append(b)
    near[b].append(a)

wait = [1]
solved[1] = 1
while True:
    target = wait.pop()
    for nex in near[target]:
        if solved[nex] != 1:
            child[target].append(nex)
            wait.append(nex)
            solved[nex] = 1
    if len(wait) == 0:
        break

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

wait = [1]

while True:
    target = wait.pop()
    for nex in child[target]:
        score[nex] += score[target]
        wait.append(nex)
    if len(wait) == 0:
        break

score.pop(0)

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

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
n,q=map(int,input().split())
l=[]
for i in range(n-1):
  l.append(list(map(int,input().split())))
l2=[]
for i in range(q):
  l2.append(list(map(int,input().split())))
connection=[[] for i in range(n)]
for i in range(n-1):
  connection[l[i][0]-1].append(l[i][1]-1)
 
L4=[]
for i in range(n):
  L4.append(0)
for i in range(q):
  L4[l2[i][0]-1]+=l2[i][1]
distance=[0 for i in range(n)]
distance[0]=L4[0]
ans=[0 for i in range(n)]
ans[0]=L4[0]
L=[0]
L2=[]
L3=[]
while len(L2)!=n and len(L)!=0:
  for j in range(len(L)):
    for k in range(len(connection[L[j]])):
      distance[connection[L[j]][k]]=distance[L[j]]+L4[connection[L[j]][k]]
      L3.append(connection[L[j]][k])
    L2.append(L[j])
  L=L3
  L3=[]
for i in range(len(distance)):
  distance[i]=str(distance[i])
print(' '.join(distance))

Submission status: Accepted

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: Accepted

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

nodes = [0 for _ in range(N)]

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

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

for i in range(N):
  if i+1 in parents:
    nodes[i] += nodes[parents[i+1]-1]

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

Submission status: Accepted

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

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

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

for root, reaf in enumerate(tree):
    for i in reaf:
        op[i] += op[root]

print(*op[1:])

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
from collections import defaultdict
from collections import deque
import sys
input = sys.stdin.readline
dd = defaultdict(list)
pq = defaultdict(int)
 
N, Q = map(int, input().split())
 
for _ in range(N-1):
    a,b = map(int, input().split())
    dd[a].append(b)
    dd[b].append(a)
 
for _ in range(Q):
    p,q = map(int, input().split())
    pq[p] += q
    
answer = [0]*N
queue = deque()
visited = {}
visited[1] = 1
queue.append(1)
 
while queue != deque():
    tmp = queue.popleft()
    answer[tmp-1] += pq[tmp]
    for i in dd[tmp]:
        if not i in visited:
            visited[i] = 1
            queue.append(i)
            answer[i-1] += answer[tmp-1]
            
print(*answer)

Submission status: Accepted

Solution code:
import sys


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


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

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

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

stack = [1]
while stack:
    label = stack.pop()
    if tree[label] != []:
        for next_label in tree[label]:
            count[next_label] += count[label]
        stack += tree[label]
ans = count[1:]

print(*ans)

Submission status: Accepted

Solution code:
def main():
    from collections import defaultdict
    from collections import deque
    import sys
    input = sys.stdin.readline
    dd = defaultdict(list)
    pq = defaultdict(int)

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

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

    for _ in range(Q):
        p,q = map(int, input().split())
        pq[p] += q
    
    answer = [0]*N
    queue = deque()
    visited = {}
    visited[1] = 1
    queue.append(1)

    while queue != deque():
        tmp = queue.popleft()
        answer[tmp-1] += pq[tmp]
        for i in dd[tmp]:
            if not i in visited:
                visited[i] = 1
                queue.append(i)
                answer[i-1] += answer[tmp-1]
            
    print(*answer)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n,q=map(int,input().split())
l=[]
for i in range(n-1):
  l.append(list(map(int,input().split())))
l2=[]
for i in range(q):
  l2.append(list(map(int,input().split())))
connection=[[] for i in range(n)]
for i in range(n-1):
  connection[l[i][0]-1].append(l[i][1]-1)
 
L4=[]
for i in range(n):
  L4.append(0)
for i in range(q):
  L4[l2[i][0]-1]+=l2[i][1]
distance=[0 for i in range(n)]
distance[0]=L4[0]
ans=[0 for i in range(n)]
ans[0]=L4[0]
L=[0]
L2=[]
L3=[]
while len(L2)!=n and len(L)!=0:
  for j in range(len(L)):
    for k in range(len(connection[L[j]])):
      distance[connection[L[j]][k]]=distance[L[j]]+L4[connection[L[j]][k]]
      L3.append(connection[L[j]][k])
    L2.append(L[j])
  L=L3
  L3=[]
for i in range(len(distance)):
  distance[i]=str(distance[i])
print(' '.join(distance))

Submission status: Accepted

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

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

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

stack = [1]
while stack:
    label = stack.pop()
    if tree[label] != []:
        for next_label in tree[label]:
            count[next_label] += count[label]
        stack += tree[label]

print(*count[1:])

Submission status: Accepted

Solution code:
import sys
 
input = sys.stdin.readline
 
 
def main():
    n, q = [int(i) for i in input().split()]
    scores = [0] * (n + 1)
    lines = sorted([[int(i) for i in input().split()] for _ in range(n - 1)])
    counter = [[int(i) for i in input().split()] for _ in range(q)]
    for index, score in counter:
        scores[index] += score
 
    for a, b in lines:
        scores[b] += scores[a]
    print(*scores[1:])
 
if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

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

stack = [1]
while stack:
    label = stack.pop()
    if tree[label] != []:
        for next_label in tree[label]:
            count[next_label] += count[label]
        stack += tree[label]

ans = count[1:]
print(*ans)

Submission status: Accepted

Solution code:
N,Q = map(int,input().split())
Ki_Oya=dict()
for i in range(N-1):
  A,B = map(int,input().split())
  Ki_Oya[B-1]=A-1
Counter_list=[0]*N
for i in range(Q):
  P,X=map(int,input().split())
  Counter_list[P-1] += X
print(Counter_list[0],end=" ")
for i in range(1,len(Counter_list)):
  Counter_list[i] += Counter_list[Ki_Oya[i]]
  print(Counter_list[i],end=" ")
print("")

Submission status: Accepted

Solution code:
n, q = map(int, input().split())
edges=[[] for i in range(n+1)]
for i in range(1,n):
	a, b=[int(i) for i in input().split()]
	edges[a].append(b)
	edges[b].append(a)
c = [0 for i in range(n+1)]
for i in range(q):
    p, x = map(int, input().split())
    c[p] += x

ind = [0 for i in range(n+1)]
ind[1] = 1
nxt = [1]
nxt_copy = []
while nxt != []:
    for i in nxt:
        for j in edges[i]:
            if ind[j] == 0:
                ind[j] = 1
                c[j] += c[i]
                nxt_copy.append(j)
    nxt = nxt_copy.copy()
    nxt_copy = []

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

Submission status: Accepted

Solution code:
def main():
  _map, _range, _int = map, range, int
  n, q = _map(_int, input().split())
  values = [0] * (n + 1)
  parents = [0] * (n + 1)
  for _ in _range(n - 1):
    a, b = _map(_int, input().split())
    parents[b] = a
  for _ in _range(q):
    p, x = _map(_int, input().split())
    values[p] += x
  for i in _range(1, n + 1):
    values[i] += values[parents[i]]
  print(*values[1:])
main()

Submission status: Accepted

Solution code:

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

# 木
G = [[] for i in range(N)]
for i in range(N-1):
    u,v = map(int,input().split())
    G[u-1].append((v-1))
    # a<bが決まっているなら、必要ない？
    # G[v-1].append((u-1))

## クエリを覚えておく
scores = [0]*N
for i in range(Q):
    p,x = map(int, input().split())
    scores[p-1] += x 

# 和をとっていく
ans = [0]*N
ans[0] = scores[0]
used = [False] * N

# 木をBFSをする
from collections import deque
used = [False] * N
used[0] = True # 始めどこから行くか
q = deque([0])
while len(q) > 0:
    v = q.popleft()
    Vs = G[v]
    for next_v in Vs: 
        if not used[next_v]:
            q.append(next_v)
            ans[next_v] = ans[v] + scores[next_v]
            used[next_v] = True
print(*ans)

Submission status: Accepted

Solution code:
import sys


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


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

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

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

stack = [1]
while stack:
    label = stack.pop()
    if tree[label] != []:
        for next_label in tree[label]:
            count[next_label] += count[label]
        stack += tree[label]

ans = count[1:]
print(*ans)

Submission status: Accepted

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

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

ps = [0] * n
for i in range(q):
    p, x = na()
    p -= 1
    ps[p] += x

stack = [0] * (n+1)
inds = [0] * (n+1)

sp = 0
stack[sp] = 0
sp += 1

while sp > 0:
    cur = stack[sp-1]
    if inds[sp-1] == len(g[cur]):
        sp -= 1
        continue
    if inds[sp-1] == 0 and sp > 1:
        ps[cur] += ps[stack[sp-2]]
    if sp == 1 or stack[sp-2] != g[cur][inds[sp-1]]:
        stack[sp] = g[cur][inds[sp-1]]
        inds[sp] = 0
        inds[sp-1] += 1
        sp += 1
        continue
    inds[sp - 1] += 1

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

Submission status: Accepted

Solution code:
def main():
  _map, _range, _int = map, range, int
  n, q = _map(_int, input().split())
  values = [0] * (n + 1)
  parents = [0] * (n + 1)
  for i in _range(n - 1):
    a, b = _map(_int, input().split())
    parents[b] = a
  for _ in _range(q):
    p, x = _map(_int, input().split())
    values[p] += x
  for i in _range(1, n + 1):
    values[i] += values[parents[i]]
  print(*values[1:])
main()

Submission status: Accepted

Solution code:
import sys


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


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

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

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

stack = [1]
while stack:
    label = stack.pop()
    if tree.get(label):
        for next_label in tree[label]:
            count[next_label] += count[label]
        stack += tree[label]

ans = count[1:]
print(*ans)

Submission status: Accepted

Solution code:
n, q = map(int, input().split())
ab = [list(map(int, input().split())) for i in range(n-1)]
ab.sort()
p = [0]*n
for i in range(q):
  i = list(map(int, input().split()))
  p[i[0] - 1] += i[1]
s = ""
for i in ab:
  p[i[1]-1] += p[i[0]-1]
print(" ".join(map(str, p)))

Submission status: Accepted

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)]

parent=[0 for i in range(n)]
for i in range(n-1):
    parent[ab[i][1]-1]=ab[i][0]
ans=[0 for i in range(n)]
for i in range(q):
    ans[px[i][0]-1]+=px[i][1]
for i in range(1,n):
    if parent[i] != 0:
        ans[i]+=ans[parent[i]-1]


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

Submission status: Accepted

Solution code:
def main():
  _map, _range, _int = map, range, int
  n, q = _map(_int, input().split())
  values = [0] * (n + 1)
  parents = [0] * (n + 1)
  for i in _range(n - 1):
    a, b = _map(_int, input().split())
    parents[b] = a
  for _ in _range(q):
    p, x = _map(_int, input().split())
    values[p] += x
  for i in _range(1, n + 1):
    if parents[i] != 0:
      values[i] += values[parents[i]]
  print(*values[1:])
main()

Submission status: Accepted

Solution code:
n,q=map(int,input().split())
a=[0]*(n-1)
c=[0 for i in range(n)]
for i in range(n-1):
  a[i]=list(map(int,input().split()))

a.sort()

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

for i in range(n-1):
  c[a[i][1]-1]+=c[a[i][0]-1]

print(*c)

Submission status: Accepted

Solution code:
n, q = list(map(int, input().split()))
# NG: [set()] * n <- all points same set
edge = [set() for _ in range(n)]
for _ in range(n - 1):
    a, b = list(map(int, input().split()))
    a -= 1
    b -= 1
    edge[a].add(b)
    edge[b].add(a)

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

score = [-1] * n
q = [(0, 0)]
while q:
    # print(*q)
    node, w = q.pop()
    w += opr[node]
    score[node] = w
    # print(*score)
    for child in edge[node]:
        if score[child] == -1:
            q.append((child, w))

print(*score)

Submission status: Accepted

Solution code:
N, Q = map(int,input().split())
G = [[] for i in range(N+ 1)]
ANS = [0] * (N + 1)
for _ in range(N - 1):
    a , b = map(int,input().split())
    G[a].append(b)
for _ in range(Q):
    p, x =map(int,input().split())
    ANS[p] += x
from collections import deque
que=deque([])
que.append(1)
while que:
    node = que.pop()
    ans = ANS[node]
    for child in G[node]:
        ANS[child] += ans
        que.append(child)
for i in range(1, N + 1):
    print(ANS[i])

Submission status: Accepted

Solution code:
from collections import defaultdict

N,Q=map(int,input().split())
l=[ tuple( map(int,input().split()) ) for i in range(N-1) ]
p_l=[ tuple( map(int,input().split()) ) for i in range(Q) ]
d=defaultdict(list)

for f,g in l:
    d[f].append(g)

d_2=defaultdict(int)
for h in range(1,N+1):
    d_2[h]=0
  
for p,x in p_l:
    d_2[p]+=x

for n in range(1,N+1):
    for m in d[n]:
        d_2[m]+=d_2[n]

print(*d_2.values())

Submission status: Accepted

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10 ** 9)

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

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

count = [0] * N

## analysis of tree structure
parent = [-1] + ['nul'] * (N - 1)
child = [[] for i in range(N)]
child[0] = repn[0]

for v in child[0]:
    parent[v] = 0

deq = deque(repn[0])

while deq:
    v = deq.popleft()
    for w in repn[v]:
        if parent[v] == w:
            pass
        else:
            parent[w] = v
            child[v].append(w)
            deq.append(w)


## soltion
for i in range(Q):
    p, x = map(int, input().split())
    p -= 1
    count[p] += x
    
deq = deque([0])
while deq:
    v = deq.popleft()
    for w in child[v]:
        count[w] += count[v]
        deq.append(w)



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