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:
import collections,sys
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
N,Q = LI()
ab = [LI() for _ in [None]*(N-1)]
px = [LI() for _ in [None]*(Q)]
ans = [0]*(N+1) #1_indexed
graph = {i:collections.deque() for i in range(1,N+1)} #1_indexed
for a,b in ab:
        graph[a].append(b)
        graph[b].append(a)
for p,x in px:
    ans[p] += x
seen = [0]*(N+1) #1_indexed
stack = []
def dfs():
    seen[1] = 1
    stack.append(1)
    while stack:
        s = stack.pop()
        if not graph[s]:
            continue
        for j in range(len(graph[s])):
            g_NO = graph[s].popleft()
            if seen[g_NO]:
                continue
            seen[g_NO] = 1
            stack.append(g_NO)
            ans[g_NO] += ans[s]
dfs()
print(*ans[1:])

Submission status: Accepted

Solution code:
from collections import Counter, deque, OrderedDict
# from copy import copy, deepcopy
# from functools import reduce
# from heapq import heapify, heappop, heappush
# from itertools import accumulate, permutations, combinations, combinations_with_replacement, groupby, product
# import math
# import numpy as np  # Pythonのみ！
# from operator import xor
# import re
# from scipy.sparse.csgraph import connected_components  # Pythonのみ！
# ↑cf.  https://note.nkmk.me/python-scipy-connected-components/
# from scipy.sparse import csr_matrix
# import statistics # Pythonのみ
# import string
import unittest
from io import StringIO
import sys
sys.setrecursionlimit(10 ** 5 + 10)


def input(): return sys.stdin.readline().strip()


def resolve():

    N, Q = map(int, input().split())
    M = N-1  # 頂点数，辺数
    ans = [0]*N

    # グラフ入力受取 (ここでは無向グラフを想定)
    G = [[] for _ in range(N)]
    for i in range(M):
        a, b = map(int, input().split())
        a -= 1
        b -= 1
        G[a].append(b)
        G[b].append(a)

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

    seen = [False]*N

    def dfs(G, v):
        seen[v] = True
        stack = deque([v])
        while stack:
            v = stack.pop()
            for next_v in G[v]:
                if seen[next_v]:
                    continue
                seen[next_v] = True
                ans[next_v] += ans[v]
                stack.append(next_v)

    # 頂点 0 をスタートとした探索
    dfs(G, 0)
    print(*ans)


resolve()

Submission status: Accepted

Solution code:
from sys import setrecursionlimit, stdin

setrecursionlimit(10 ** 9)

def input():
    return stdin.readline()

n, q = map(int, input().split())
root = [[] for _ in range(n)]
ans = [0 for _ in range(n)]
for _ in range(n - 1):
    a, b = map(int, input().split())
    root[a - 1].append(b - 1)
    root[b - 1].append(a - 1)
for _ in range(q):
    p, x = map(int, input().split())
    ans[p - 1] += x
    
def dfs(pos, before):
    for next_pos in root[pos]:
        if next_pos == before:
            continue
        ans[next_pos] += ans[pos]
        dfs(next_pos, pos)

dfs(0, -1)

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

Submission status: Accepted

Solution code:
cin = open(0).read().strip().split('\n')
n,q=map(int, cin[0].split(' '))
ab = [tuple(map(int, a.split(' '))) for a in cin[1:n]]
px = [tuple(map(int, a.split(' '))) for a in cin[n:n+q]]

import sys
sys.setrecursionlimit(10**9)

def dfs(g, idx, seen):
    global score

    seen[idx] = True
    for i in g[idx]:
        if seen[i]: continue
        score[i] += score[idx]
        dfs(g, i, seen)

g = [[] for _ in range(n)]
for abi in ab:
    # 無向グラフはお互いが参照し合う
    g[abi[0]-1].append(abi[1]-1)
    g[abi[1]-1].append(abi[0]-1)

score = [0]*n
for pxi in px:
    score[pxi[0]-1] += pxi[1]

seen = [False]*n
dfs(g, 0, seen)

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)

n, q = map(int,input().split())
tree = [list(map(int,input().split())) for _ in range(n-1)]
score = [list(map(int,input().split())) for _ in range(q)]

graph = [[] for _ in range(n+1)]
for t in tree:
    graph[t[0]].append(t[1])
    graph[t[1]].append(t[0])
#print(graph)
#[[], [2], [1, 3, 4], [2], [2]]

value = [0]*(n+1)
for s in score:
    value[s[0]] += s[1]

#print(value)
# [0, 100, 10, 1, 0]

q = [(1,0)]
while q:
    target,parent = q.pop()
    value[target] += value[parent]
    for t in graph[target]:
        if t == parent:
            continue
        else:
            q.append((t,target))

v = value[1:]
print(*v)

Submission status: Accepted

Solution code:
cin = open(0).read().strip().split('\n')
n, q = map(int, cin[0].split(' '))
ab = [tuple(map(int, a.split(' '))) for a in cin[1:n]]
px = [tuple(map(int, a.split(' '))) for a in cin[n:n+q]]

import sys
sys.setrecursionlimit(10**9)

def dfs(g, seen, idx):
    global score

    seen[idx] = True
    for i in g[idx]:
        if seen[i]: continue
        score[i] += score[idx]
        dfs(g, seen, i)

g = [[] for _ in range(n)]
for abi in ab:
    g[abi[0]-1].append(abi[1]-1)
    g[abi[1]-1].append(abi[0]-1)

score = [0]*n
for pxi in px:
    score[pxi[0]-1] += pxi[1]

seen = [False]*n
dfs(g, seen, 0)

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

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline

def dfs(p, v, num):
    global g, plus_list, ans
    tmp = num + plus_list[v]
    for x in g[v]:
        if x == p:
            continue
        dfs(v, x, tmp)
    ans[v] = tmp
    
def main():
    global g, plus_list, ans
    N, Q = map(int, input().split())
    g = [[] for i in range(N)] 
    for i in range(N-1):
        a, b = map(int, input().split())
        a -= 1
        b -= 1
        g[a].append(b)
        g[b].append(a)

    plus_list = [0] * N
    for i in range(Q):
        q, y = map(int, input().split())
        plus_list[q-1] += y

    ans = [0] * N
    
    dfs(-1, 0, 0)
    print(*ans)
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
readline = sys.stdin.readline

def dfs(p, v, num):
    global g, plus_list, ans
    tmp = num + plus_list[v]
    for x in g[v]:
        if x == p:
            continue
        dfs(v, x, tmp)
    ans[v] = tmp
    
def main():
    global g, plus_list, ans
    N, Q = map(int, readline().split())
    g = [[] for i in range(N)] 
    for i in range(N-1):
        a, b = map(int, readline().split())
        a -= 1
        b -= 1
        g[a].append(b)
        g[b].append(a)

    plus_list = [0] * N
    for i in range(Q):
        q, y = map(int, readline().split())
        plus_list[q-1] += y

    ans = [0] * N
    
    dfs(-1, 0, 0)
    print(*ans)
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(202020)

n, q = map(int, input().split())
to = [deque() for _ in range(n)]
score = [0 for _ in range(n)]
for i in range(n-1):
    a, b = map(int, input().split())
    a -= 1; b -= 1
    to[a].append(b)
    to[b].append(a)
for i in range(q):
    p, x = map(int, input().split())
    p -= 1
    score[p] += x

visited = [False for _ in range(n)]
def dfs(v):
    visited[v] = True
    stack = deque([v])
    while len(stack) > 0:
        u = stack[-1]
        if len(to[u]) > 0:
            w = to[u].popleft()
            if visited[w]:
                continue
            score[w] += score[u]
            visited[w] = True
            stack.append(w)
        else:
            stack.pop()

dfs(0)
print(*score)

Submission status: Accepted

Solution code:
from collections import defaultdict
N, Q = map(int, input().split())
E = defaultdict(list)
for i in range(N-1):
    a, b = map(int, input().split())
    E[a-1].append(b-1)
    E[b-1].append(a-1)
d = [0]*N
ok = [True]*N
cnt = [0]*N
for i in range(Q):
    p, x = map(int, input().split())
    cnt[p-1] += x
stack = [0]
while stack:
    p = stack.pop()
    d[p] += cnt[p]
    ok[p] = False
    for np in E[p]:
        if ok[np]:
            cnt[np] += cnt[p]
            stack.append(np)

print(*d)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline    ####
int1 = lambda x: int(x) - 1
def II(): return int(input())

def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())

def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]

def printlist(lst, k='\n'): print(k.join(list(map(str, lst))))
INF = float('inf')

def solve():
    n, q = MI()
    e = [[] for _ in range(n)]
    for _ in range(n-1):
        a, b = MI1()
        e[a].append(b)
        e[b].append(a)

    point = [0]*n
    for _ in range(q):
        p, x = MI()
        p -= 1
        point[p] += x

    # print(point)

    def dfs(v, v_pre=-1, pp=0):
        # ans = pp + point[v]
        # print(v)
        point[v] += pp
        for nv in e[v]:
            if nv == v_pre: continue
            dfs(nv, v, point[v])

    dfs(0)
    printlist(point, ' ')


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline    ####
int1 = lambda x: int(x) - 1
def II(): return int(input())

def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())

def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]

def printlist(lst, k='\n'): print(k.join(list(map(str, lst))))
INF = float('inf')
from collections import deque
def solve():
    n, q = MI()
    e = [[] for _ in range(n)]
    for _ in range(n - 1):
        a, b = MI1()
        e[a].append(b)
        e[b].append(a)

    point = [0] * n
    for _ in range(q):
        p, x = MI()
        p -= 1
        point[p] += x

    d = deque([(0, point[0])])
    used = [0] * n
    used[0] = 1

    l = 1
    while l > 0:
        v, p = d.popleft()
        l -= 1
        for nv in e[v]:
            if used[nv]: continue
            used[nv] = 1
            point[nv] += p
            d.append((nv, point[nv]))
            l += 1

    printlist(point, " ")

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)
# input = sys.stdin.readline    ####
int1 = lambda x: int(x) - 1
def II(): return int(input())

def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())

def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]

def printlist(lst, k='\n'): print(k.join(list(map(str, lst))))
INF = float('inf')
from collections import deque
def solve():
    n, q = MI()
    e = [[] for _ in range(n)]
    for _ in range(n - 1):
        a, b = MI1()
        e[a].append(b)
        e[b].append(a)

    point = [0] * n
    for _ in range(q):
        p, x = MI()
        p -= 1
        point[p] += x

    d = deque([(0, point[0])])
    used = [0] * n
    used[0] = 1

    l = 1
    while l > 0:
        v, p = d.popleft()
        l -= 1
        for nv in e[v]:
            if used[nv]: continue
            used[nv] = 1
            point[nv] += p
            d.append((nv, point[nv]))
            l += 1

    printlist(point, " ")

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)
# input = sys.stdin.readline    ####
int1 = lambda x: int(x) - 1
def II(): return int(input())

def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())

def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]

def printlist(lst, k='\n'): print(k.join(list(map(str, lst))))
INF = float('inf')
from collections import deque
def solve():
    n, q = MI()
    e = [[] for _ in range(n)]
    for _ in range(n - 1):
        a, b = MI1()
        e[a].append(b)
        e[b].append(a)

    point = [0] * n
    for _ in range(q):
        p, x = MI()
        p -= 1
        point[p] += x

    d = deque([(0, point[0])])
    used = [False] * n
    used[0] = True

    l = 1
    while l > 0:
        v, p = d.popleft()
        l -= 1
        for nv in e[v]:
            if used[nv]: continue
            used[nv] = True
            point[nv] += p
            d.append((nv, point[nv]))
            l += 1

    printlist(point, " ")

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)
# input = sys.stdin.readline    ####
int1 = lambda x: int(x) - 1
def II(): return int(input())

def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())

def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]

def printlist(lst, k='\n'): print(k.join(list(map(str, lst))))
INF = float('inf')
from collections import deque
def solve():
    n, q = MI()
    e = [[] for _ in range(n)]
    for _ in range(n - 1):
        a, b = MI1()
        e[a].append(b)
        e[b].append(a)

    point = [0] * n
    for _ in range(q):
        p, x = MI()
        p -= 1
        point[p] += x

    d = deque([(0, point[0])])
    used = [False] * n
    used[0] = True

    while len(d) > 0:
        v, p = d.popleft()
        for nv in e[v]:
            if used[nv]: continue
            used[nv] = True
            point[nv] += p
            d.append((nv, point[nv]))

    printlist(point, " ")

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

from collections import deque 
def main():
    N, Q = map(int, readline().split())
    to = [[] for _ in range(N)]
    for _ in range(N-1):
        a, b = map(int, readline().split())
        a -= 1
        b -= 1
        to[a].append(b)
        to[b].append(a)
    score = [0 for  _ in range(N)]
    for _ in range(Q):
        p, x = map(int, readline().split()) 
        p -= 1
        score[p] += x  
    
    dq = deque() 
    dq.append(0)
    done = [0 for _ in range(N)]
    done[0] = 1

    while len(dq)>0:
        v = dq.popleft()
        for nx in to[v]:
            if done[nx]:
                continue
            score[nx] += score[v]
            done[nx] = 1
            dq.append(nx)
    for i in range(N):
        if i==N-1:
            print(score[i])
        else:
            print(score[i], end=' ')
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque
def dfs(graph, N, start, points):
    visited = [0] * N
    visited[start] = 1
    stack = deque([(start, points[start])])
    ret = [0] * N
    while stack:
        edge, point = stack.pop()
        ret[edge] = point
        for e in graph[edge]:
            if not visited[e]:
                visited[e] = 1
                stack.append((e, point + points[e]))
    return ret

N, Q = map(int, input().split())
graph = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = map(lambda n: int(n) - 1, input().split())
    graph[a].append(b)
    graph[b].append(a)
points = [0] * N
for _ in range(Q):
    p, x = map(int, input().split())
    points[p - 1] += x
print(*dfs(graph, N, 0, points))

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines

def main():
    N,Q,*m = map(int, read().split())
    AB = m[:2*(N-1)]
    PX = m[2*(N-1):]

    E = [[] for _ in range(N+1)]
    for a, b in zip(*[iter(AB)]*2):
        E[a].append(b)
        E[b].append(a)

    cost = [0] * (N+1)
    for p, x in zip(*[iter(PX)]*2):
        cost[p] += x

    seen = [-1] * (N+1)
    seen[1] = cost[1]
    stack = [1]
    while stack:
        v = stack.pop()
        for e in E[v]:
            if seen[e] == -1:
                seen[e] = seen[v] + cost[e]
                stack.append(e)

    print(*seen[1:])
    

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque
N,Q=map(int,input().split())
nondirtree=[[] for _ in range(N)]
dirtree=[[] for _ in range(N)]
for i in range(N-1):
    a,b=map(int,input().split())
    nondirtree[a-1].append(b-1)
    nondirtree[b - 1].append(a - 1)
#points=[tuple(map(int,input().split())) for _ in range(Q)]
score=[0]*N
for i in range(Q):
    point,sc=map(int,input().split())
    score[point-1]=score[point-1]+sc
#print(points)
v=0
d=deque()
d.append(v)
seen=[0]*N
seen[0]=1
ans=[0]*N
while len(d)!=0:
    v=d.popleft()
    for j in nondirtree[v]:
        if seen[j]==0:
            dirtree[v].append(j)
            seen[j]=1
            d.append(j)
    #print(d,seen,dirtree)
    #input(
v=0
d=deque()
d.append(v)
#print(dirtree)
ans[0]=score[0]
while len(d)!=0:
    v=d.popleft()
    for j in dirtree[v]:
        ans[j]=ans[v]+score[j]
        d.append(j)
    #input()
    #print(ans)
print(*ans,sep=" ")

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
from collections import deque
N,Q=map(int,input().split())
nondirtree=[[] for _ in range(N)]
dirtree=[[] for _ in range(N)]
for i in range(N-1):
    a,b=map(int,input().split())
    nondirtree[a-1].append(b-1)
    nondirtree[b - 1].append(a - 1)
#points=[tuple(map(int,input().split())) for _ in range(Q)]
score=[0]*N
for i in range(Q):
    point,sc=map(int,input().split())
    score[point-1]=score[point-1]+sc
#print(points)
v=0
d=deque()
d.append(v)
seen=[0]*N
seen[0]=1
ans=[0]*N
while len(d)!=0:
    v=d.popleft()
    for j in nondirtree[v]:
        if seen[j]==0:
            dirtree[v].append(j)
            seen[j]=1
            d.append(j)
    #print(d,seen,dirtree)
    #input(
v=0
d=deque()
d.append(v)
#print(dirtree)
ans[0]=score[0]
while len(d)!=0:
    v=d.popleft()
    for j in dirtree[v]:
        ans[j]=ans[v]+score[j]
        d.append(j)
    #input()
    #print(ans)
print(*ans,sep=" ")

Submission status: Accepted

Solution code:
from collections import OrderedDict
import sys
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
#初期データ、構造
N,Q = (int(x) for x in input().split())
connection ={i:set() for i in range(1,N+1)}
for i in range(N-1):
    a,b = (int(x) for x in input().split())
    connection[a].add(b)
    connection[b].add(a)
#point =OrderedDict({i:0 for i in range(1,N+1)})
point ={i:0 for i in range(1,N+1)}
for i in range(Q):
    p,x = (int(x) for x in input().split())
    point[p] +=x

def DFS(now,prev = -1):
    for next in connection[now]:
        if next == prev:
            continue
        point[next] +=point[now] 
        DFS(next,now)

DFS(1)
print(*point.values())

Submission status: Accepted

Solution code:
n,q = map(int,input().split())
from collections import deque
s = [[] for i in range(n)]
for i in range(n-1):
    a,b = map(int,input().split())
    a = a-1
    b = b-1
    s[a].append(b)
    s[b].append(a)
count = [0 for i in range(n)]
for i in range(q):
    p,x = map(int,input().split())
    count[p-1] += x
ans = [-1 for i in range(n)]
ans[0] = count[0]
d = deque([(0,0)])
while d:
    u,v = d.pop()
    ans[u] = v + count[u]
    for b in s[u]:
        if ans[b] == -1:
            d.append((b,ans[u]))
        else:
            continue
for i in range(n):
    print(ans[i])

Submission status: Accepted

Solution code:
n,q = map(int,input().split())
from collections import deque
s = [[] for i in range(n)]
for i in range(n-1):
    a,b = map(int,input().split())
    a = a-1
    b = b-1
    s[a].append(b)
    s[b].append(a)
count = [0 for i in range(n)]
for i in range(q):
    p,x = map(int,input().split())
    count[p-1] += x
ans = [-1 for i in range(n)]
ans[0] = count[0]
d = deque([(0,0)])
while d:
    u,v = d.popleft()
    ans[u] = v + count[u]
    for b in s[u]:
        if ans[b] == -1:
            d.append((b,ans[u]))
        else:
            continue
for i in range(n):
    print(ans[i])

Submission status: Accepted

Solution code:
import collections,sys
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
n,q=LI()
ab=[LI() for _ in range(n-1)]
px=[LI() for _ in range(q)]
ans=[0]*(n+1)
graph={i:collections.deque() for i in range(1,n+1)}
for a,b in ab:
    graph[a].append(b)
    graph[b].append(a)
for p,x in px:
    ans[p]+=x
seen=[0]*(n+1)
stack=[]
def dfs():
    seen[1]=1
    stack.append(1)
    while stack:
        s=stack.pop()
        if not graph[s]:
            continue
        for j in range(len(graph[s])):
            gno=graph[s].popleft()
            if seen[gno]:
                continue
            seen[gno]=1
            stack.append(gno)
            ans[gno]+=ans[s]
dfs()
print(*ans[1:])

Submission status: Accepted

Solution code:
import collections,sys
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
n,q=LI()
ab=[LI() for _ in [None]*(n-1)]
px=[LI() for _ in [None]*q]
ans=[0]*(n+1)
graph={i:collections.deque() for i in range(1,n+1)}
for a,b in ab:
    graph[a].append(b)
    graph[b].append(a)
for p,x in px:
    ans[p]+=x
seen=[0]*(n+1)
stack=[]
def dfs():
    seen[1]=1
    stack.append(1)
    while stack:
        s=stack.pop()
        if not graph[s]:
            continue
        for j in range(len(graph[s])):
            gno=graph[s].popleft()
            if seen[gno]:
                continue
            seen[gno]=1
            stack.append(gno)
            ans[gno]+=ans[s]
dfs()
print(*ans[1:])

Submission status: Accepted

Solution code:
from collections import deque

N,Q = list(map(int, input().split()))
tre = [[] for _ in range(N)]
val = [0] * N
for i in range(N-1):
    a,b = list(map(int, input().split()))
    tre[a-1].append(b-1)
    tre[b-1].append(a-1)

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

stack = deque([0])
visited = [False] * N
visited[0] = True
while stack:
    cur = stack.pop()
    for target in tre[cur]:
        if visited[target]:
            continue
        visited[target] = True
        stack.append(target)
        val[target] += val[cur]

print(*val)

Submission status: Accepted

Solution code:
# D - Ki

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

children = [[] for _ in range(N)]
points = [0] * N

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

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

stack = []
stack.append(0)
visited = [False] * N
while stack:
    key = stack.pop()
    visited[key] = True
    for child in children[key]:
        if visited[child] == False:
            points[child] += points[key]
            stack.append(child)

print(*points)

Submission status: Accepted

Solution code:
# D - Ki

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

children = [[] for _ in range(N)]
points = [0] * N

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

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

stack = []
stack.append(0)
visited = [False] * N
while stack:
    key = stack.pop()
    for child in children[key]:
        if visited[child] == True:
            continue
        points[child] += points[key]
        visited[key] = True
        stack.append(child)

print(*points)

Submission status: Accepted

Solution code:
N,Q = [int(x) for x in input().split()]
ki = [0]*N
tr = [[] for _ in range(N)]

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

for i in range(Q):
    position,val = [int(x) for x in input().split()]
    ki[position-1] += val

stack =[0]
visited = set()
visited.add(0)

while stack:
    i = stack.pop()
    for j in tr[i]:
        if j in visited:
            continue
        visited.add(j)
        ki[j] += ki[i]
        stack.append(j)

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

Submission status: Accepted

Solution code:
from collections import deque
n,q = map(int,input().split())
ad_ls = [[] for _ in range(n+1)]
count_ls = [0] * (n+1)
done_ls = [0] * (n+1)
for i in range(n-1):
    a,b = map(int,input().split())
    ad_ls[a].append(b)
    ad_ls[b].append(a)
for i in range(q):
    p,x = map(int,input().split())
    count_ls[p] += x
def turn(ver):
    if ad_ls[ver]:
        for ad in  ad_ls[ver]:
            if not done_ls[ad]:
                count_ls[ad] += count_ls[ver]
                q.append(ad)
    done_ls[ver] = 1
q = deque()
q.append(1)
while len(q) > 0:
    target = q.popleft()
    turn(target)
count_ls = list(map(str, count_ls))
print(' '.join(count_ls[1:]))

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)
    tree[b].append(a)

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

from collections import deque
todo = deque([(1,0)])

while len(todo) > 0:
    child,parent = todo.pop()
    value[child] += value[parent]
    for next in tree[child]:
        if next == parent:
            continue
        else:
            todo.append((next,child))

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

Submission status: Accepted

Solution code:
from sys import stdin
from collections import deque
def main():
    #入力
    readline=stdin.readline
    n,q=map(int,readline().split())
    G=[[] for _ in range(n+1)]
    for i in range(n-1):
        a,b=map(int,readline().split())
        G[a].append(b)
        G[b].append(a)
    px=[0]*(n+1)
    for i in range(q):
        p,x=map(int,readline().split())
        px[p]+=x

    cnt=[0]*(n+1)
    flags=[False]*(n+1)
    d=deque([[1,px[1]]])
    while len(d)>0:
        now=d.pop()
        flags[now[0]]=True
        cnt[now[0]]=now[1]
        for nex in G[now[0]]:
            if flags[nex]==False:
                d.append([nex,now[1]+px[nex]])

    print(*cnt[1:])

if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import numpy as np
from collections import deque
import heapq
import collections
import itertools
import bisect


mod = 10 ** 9 + 7
N, Q = list(map(int, input().split()))
tree = [[] for i in range(N)]
for i in range(N-1):
    a, b = map(int, input().split())
    tree[a-1].append(b-1)
    tree[b-1].append(a-1)
counter = [0]*N
p_lis = [0] * Q
x_lis = [0] * Q
for i in range(Q):
    p, x = map(int, input().split())
    counter[p-1] += x
stack = deque([0])
visited = [0]*N
visited[0] = 1  # ルートからたどっていく
while stack:
    node = stack.pop()
    for child in tree[node]:
        if visited[child] == 1:
            continue
        stack.append(child)
        visited[node] = 1
        counter[child] += counter[node]


print(*counter)

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

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

anss = [0] * N
for p, x in querys:
    anss[p-1] += x

def bfs(vSt):
    useds = [False] * (N)
    useds[vSt] = True
    Q = deque([vSt])
    while Q:
        vNow = Q.popleft()
        ans = anss[vNow]
        for v2 in adjL[vNow]:
            if not useds[v2]:
                anss[v2] += ans
                Q.append(v2)
                useds[v2] = True

bfs(0)

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

Submission status: Accepted

Solution code:
import sys

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

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

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

stack = [1]
visited = [False for _ in range(N + 1)]
visited[1] = True

while stack:
    i = stack.pop()
    for j in E[i]:
        if visited[j]:
            continue
        visited[j] = True
        stack.append(j)
        X[j] += X[i]

print(*X[1:])

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)


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


def dfs(now, prev=-1):
    for next in tree[now]:
        # 1個前のノードを参照した時はcontinue
        if next == prev:
            continue

        # 現在のポイントを次のノードへ加算して累積和をとる
        point[next] += point[now]

        # 次のノードへ
        dfs(next, now)


N, Q = map(int, input().split())
tree = [[] for _ in range(N)]
point = [0]*N

# 木構造を2次元配列で表現。要素Xのノードからつながっているノード番号が格納される。
for _ in range(N-1):
    a, b = map(int, input().split())
    tree[a-1].append(b-1)
    tree[b-1].append(a-1)

# 各ノードのポイントを求める
for _ in range(Q):
    p, x = map(int, input().split())
    point[p-1] += x

dfs(0)
print(*point)

Submission status: Accepted

Solution code:
import sys
from collections import deque

sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline

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

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

P = [0] * (N + 1)

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

que = deque()
que.append((1, 0))

while que:
    v, parent = que.popleft()
    P[v] += P[parent]
    for next_v in edges[v]:
        if next_v == parent: continue
        que.append((next_v, v))

# def f(v, parent=0):
#     P[v] += P[parent]
#
#     for next_v in edges[v]:
#         if next_v == parent: continue
#         f(next_v, v)
#
#
# f(1)
print(*[P[i] for i in range(1, N + 1)])