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 sys
sys.setrecursionlimit(500000) 
input=sys.stdin.readline

N,M = map(int,input().split())
ans=[0]*N
a = [list(map(int, input().split())) for _ in range(N-1)]

for _ in range(M):
    e,f = list(map(int, input().split()))
    ans[e-1] += f

trees = {}
for word in a:
    trees.setdefault(word[0], []).append(word[1])
    trees.setdefault(word[1], []).append(word[0])
    

def sumup(ne,parent):
    global ans
    if ne in trees:    
        for k in trees[ne]:
            if k != parent:
                ans[k-1] += ans[ne-1]
                sumup(k,ne)

sumup(1,0)
for i in ans:
    print(i)

Submission status: Accepted

Solution code:
n, q = map(int,input().split())
cnt = [0] * (n+1)
tree = [[] for _ in range(n+1)]
seen = [0] * (n+1)
todo = [1]
for i in range(n-1):
    a, b = map(int,input().split())
    tree[a].append(b)
    tree[b].append(a)
for _ in range(q):
    p,x = map(int,input().split())
    cnt[p] += x

while todo != []:
    i = todo.pop()
    seen[i] = 1
    for j in tree[i]:
        if seen[j] == 0:
            todo.append(j)
            cnt[j] += cnt[i]
print(*cnt[1:])

Submission status: Accepted

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

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)


dir_edge = [[] for i in range(n)]

for e in edge:
    dir_edge[e[0]-1].append(e[1]-1)
    dir_edge[e[1]-1].append(e[0]-1)
#print(dir_edge)


ans = [0]*n
for v in add_list:
    ans[v[0]-1] += v[1]
#print(add_value)


def dfs(index, parent):
    if parent != -1:
        ans[index] += ans[parent]
    for i in dir_edge[index]:
        if (parent != i):
            dfs(i,index)

dfs(0, -1)
print(*ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque
def input():
    return sys.stdin.readline()[:-1]
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
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()  
    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: Accepted

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


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

def dfs(p, s, checked, score):
    #print(p, s, score)
    ns = s + score[p]
    score[p] += s
    for q in graph[p]:
        if not checked[q]:
            checked[q] = True
            score = dfs(q, ns, checked, score)
    return score


def main():


    score = [0 for _ in range(N)]
    for p, x in PX:
        score[p-1] += x

    checked = [False for _ in range(N)]
    checked[0] = True
    
    ans = dfs(0, 0, checked, score)
    print(' '.join([str(a) for a in ans]))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(5 * 10**5)
input=sys.stdin.readline
 
N, Q = list(map(int, input().split()))
 
M = [[] for _ in range(N)]
for _ in range(N-1):
    a, b = list(map(int, input().split()))
    M[a-1].append(b-1)
    M[b-1].append(a-1)
 
ans = [0] * N
for _ in range(Q):
    p, x = list(map(int, input().split()))
    ans[p-1] += x
 
def setAnswer(parent, number):
    ans[number] += ans[parent]
 
    for i in M[number]:
        if i != parent:
            setAnswer(number, i)
 
for i in M[0]:
    setAnswer(0, i)
 
print(' '.join(map(str, ans)))

Submission status: Accepted

Solution code:
from collections import deque
import sys
input=sys.stdin.readline
def main():
  a,b=map(int,input().split())
  e=[[]for i in range(a)]

  for i in range(a-1):
    c1,c2=map(int,input().split())
    e[c1-1].append(c2-1)
    e[c2-1].append(c1-1)

  g=[[]for i in range(a)]
  f=deque([(0,-1)])
  ans=[0 for _ in range(a)]
  for i in range(b):
    ten,p=map(int,input().split())
    ans[ten-1]+=p
  i=0
  while len(f)!=0:
    i,fr=f.pop()
    for j in e[i]:
      if j==fr:
        continue
      else:
        ans[j]+=ans[i]
        f.append((j,i)) 
  print(*ans)

if __name__ == '__main__':  
  main()

Submission status: Accepted

Solution code:
from collections import deque
import sys
input=sys.stdin.readline
a,b=map(int,input().split())
e=[[]for i in range(a)]

for i in range(a-1):
  c1,c2=map(int,input().split())
  e[c1-1].append(c2-1)
  e[c2-1].append(c1-1)

g=[[]for i in range(a)]
f=deque([(0,-1)])
ans=[0 for _ in range(a)]
for i in range(b):
  ten,p=map(int,input().split())
  ans[ten-1]+=p
i=0
while len(f)!=0:
  i,fr=f.pop()
  for j in e[i]:
    if j==fr:
      continue
    else:
      ans[j]+=ans[i]
      f.append((j,i)) 
print(*ans)

Submission status: Accepted

Solution code:
from collections import deque
import sys
def main():
  a,b=map(int,sys.stdin.readline().split())
  e=[[]for i in range(a)]

  for i in range(a-1):
    c1,c2=map(int,sys.stdin.readline().split())
    e[c1-1].append(c2-1)
    e[c2-1].append(c1-1)

  g=[[]for i in range(a)]
  f=deque([(0,-1)])
  ans=[0 for _ in range(a)]
  for i in range(b):
    ten,p=map(int,input().split())
    ans[ten-1]+=p
  i=0
  while len(f)!=0:
    i,fr=f.pop()
    for j in e[i]:
      if j==fr:
        continue
      else:
        ans[j]+=ans[i]
        f.append((j,i)) 
  print(*ans)
if __name__ == '__main__':  
  main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline

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

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

def dfs(v, p):
    for u in edge[v]:
        if u == p:
            continue
        imos[u] += imos[v]
        dfs(u, v)

dfs(0, -1)
print(' '.join([str(x) for x in imos]))

Submission status: Accepted

Solution code:
import sys
from collections import deque
input = sys.stdin.readline
n, q = map(int, input().split())

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

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

q = deque([(0, -1)])
while q:
    v, p = q.pop()
    for u in edge[v]:
        if u == p:
            continue
        imos[u] += imos[v]
        q.append((u, v))

print(' '.join([str(x) for x in imos]))

Submission status: Accepted

Solution code:
from collections import deque
import sys
def main():
  a,b=map(int,sys.stdin.readline().split())
  e=[[]for i in range(a)]

  for i in range(a-1):
    c1,c2=map(int,sys.stdin.readline().split())
    e[c1-1].append(c2-1)
    e[c2-1].append(c1-1)

  g=[[]for i in range(a)]
  f=deque()
  f.append((0,-1))
  ans=[0 for _ in range(a)]
  for i in range(b):
    ten,p=map(int,input().split())
    ans[ten-1]+=p
  i=0
  while len(f)!=0:
    i,fr=f.popleft()
    for j in e[i]:
      if j==fr:
        continue
      else:
        ans[j]+=ans[i]
        f.append((j,i)) 
  print(*ans)
if __name__ == '__main__':  
  main()

Submission status: Accepted

Solution code:
from collections import deque
import sys
def main():
  a,b=map(int,sys.stdin.readline().split())
  e=[[]for i in range(a)]

  for i in range(a-1):
    c1,c2=map(int,sys.stdin.readline().split())
    e[c1-1].append(c2-1)
    e[c2-1].append(c1-1)

  g=[[]for i in range(a)]
  f=deque()
  f.append((0,-1))
  ans=[0 for _ in range(a)]
  for i in range(b):
    ten,p=map(int,input().split())
    ans[ten-1]+=p
  i=0
  while len(f)!=0:
    i,fr=f.popleft()
    for j in e[i]:
      if j==fr:
        continue
      else:
        ans[j]+=ans[i]
        f.append([j,i]) 
  print(*ans)
if __name__ == '__main__':  
  main()

Submission status: Accepted

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 + 1)]
    for _ in range(N - 1):
        a, b = parse(int, int)
        edges[a] += [b]
        edges[b] += [a]
    vals = [0] * (N + 1)
    for _ in range(Q):
        p, x = parse(int, int)
        vals[p] += x

    counter = [0] * (N + 1)
    que = deque()
    que.append((1, 0))
    alr = [False] * (N + 1)
    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]))

    print(*counter[1:])

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

Submission status: Accepted

Solution code:
# ABC138D - Ki
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

def dfs(v: int, p: int, G: "List[List[int]]", cnt: "List[int]"):
    for u in G[v]:
        if u != p:  # p: parent -> skip
            cnt[u] += cnt[v]  # cumulative sum
            dfs(u, v, G, cnt)
            
def main():
    N, Q = tuple(map(int, input().split()))  # vertices and queues
    E = tuple(tuple(map(int, input().split())) for _ in range(N - 1))
    P = tuple(tuple(map(int, input().split())) for _ in range(Q))
    G = [[] for _ in range(N + 1)]  # graph, N+1: 1-idx -> 0-idx
    for a, b in E:
        G[a] += [b]
        G[b] += [a]
    cnt = [0] * (N + 1)
    for p, x in P:
        cnt[p] += x  # increase vertex p by x
    dfs(1, -1, G, cnt)
    print(*cnt[1:])
    

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque
import sys
def main():
  a,b=map(int,sys.stdin.readline().split())
  e=[[]for i in range(a)]

  for i in range(a-1):
    c1,c2=map(int,sys.stdin.readline().split())
    e[c1-1].append(c2-1)
    e[c2-1].append(c1-1)

  g=[[]for i in range(a)]
  f=deque()
  f.append((0,-1))
  ans=[0 for _ in range(a)]
  for i in range(b):
    ten,p=map(int,input().split())
    ans[ten-1]+=p
  i=0
  while len(f)!=0:
    i,fr=f.popleft()
    for j in e[i]:
      if j==fr:
        continue
      else:
        ans[j]+=ans[i]
        f.append((j,i)) 
  print(*ans)
  
main()

Submission status: Accepted

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 + 1)]
    for _ in range(N - 1):
        a, b = parse(int, int)
        edges[a] += [b]
        edges[b] += [a]
    vals = [0] * (N + 1)
    for _ in range(Q):
        p, x = parse(int, int)
        vals[p] += x

    counter = [0] * (N + 1)
    que = [(1, 0)]
    alr = [False] * (N + 1)
    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[1:]:
        print(v)

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

Submission status: Accepted

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 + 1)]
    for _ in range(N - 1):
        a, b = parse(int, int)
        edges[a] += [b]
        edges[b] += [a]
    vals = [0] * (N + 1)
    for _ in range(Q):
        p, x = parse(int, int)
        vals[p] += x

    counter = [0] * (N + 1)
    que = deque()
    que.append((1, 0))
    alr = [False] * (N + 1)
    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[1:]:
        print(v)

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

Submission status: Accepted

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)

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

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
      values[other] += values[cur]
      bfs_queue_len += 1
      bfs_queue.append(other)

print(*values)

Submission status: Accepted

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]
        edges[b] += [a]
    vals = [0] * N
    for _ in range(Q):
        p, x = parse(int1, int)
        vals[p] += x

    counter = [0] * N
    que = deque()
    que.append((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: Accepted

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]
        edges[b] += [a]
    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: Accepted

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)
visit = [False]*(N+1)
for _ in range(N-1):
    a, b = map(int, input().split())
    tree[a].append(b)
    tree[b].append(a)

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


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

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

Submission status: Accepted

Solution code:
from collections import deque
def main():
  a,b=map(int,input().split())
  e=[[]for i in range(a)]

  for i in range(a-1):
    c1,c2=map(int,input().split())
    e[c1-1].append(c2-1)
    e[c2-1].append(c1-1)

  g=[[]for i in range(a)]
  f=deque()
  f.append((0,-1))
  ans=[0 for _ in range(a)]
  for i in range(b):
    ten,p=map(int,input().split())
    ans[ten-1]+=p
  i=0
  while len(f)!=0:
    i,fr=f.popleft()
    for j in e[i]:
      if j==fr:
        continue
      else:
        ans[j]+=ans[i]
        f.append([j,i]) 
  print(*ans)
  
main()

Submission status: Accepted

Solution code:
from collections import deque
a,b=map(int,input().split())
e=[[]for i in range(a)]

for i in range(a-1):
  c1,c2=map(int,input().split())
  e[c1-1].append(c2-1)
  e[c2-1].append(c1-1)

g=[[]for i in range(a)]
f=deque()
f.append((0,-1))
ans=[0 for _ in range(a)]
for i in range(b):
  ten,p=map(int,input().split())
  ans[ten-1]+=p
i=0
while len(f)!=0:
  i,fr=f.popleft()
  for j in e[i]:
    if j==fr:
      continue
    else:
      ans[j]+=ans[i]
      f.append([j,i]) 
print(*ans)

Submission status: Accepted

Solution code:
n, q = map(int, input().split())
g = [[] for _ in range(n)]
for i in range(n - 1):
  a, b = map(int, input().split())
  g[a - 1].append(b - 1)
  g[b - 1].append(a - 1)
li = [0] * n
for i in range(q):
  p, x = map(int, input().split())
  li[p - 1] += x
s = [0]
done = [0] * n
done[0] = 1
while s:
  d = s.pop()
  for node in g[d]:
    if done[node] == 0:
      li[node] += li[d]
      s.append(node)
      done[node] = 1
print(' '.join(map(str, li)))

Submission status: Accepted

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)
    g[b].append(a)
c=[0]*(n+1)
que=[1]
done=[0]*(n+1)
done[1]=1
for _ in range(q):
    p,x=map(int,input().split())
    c[p]+=x
while que:
    d=que.pop()
    for node in g[d]:
        if not done[node]:
            c[node]+=c[d]
            que.append(node)
            done[node]+=1
print(*c[1:])

Submission status: Accepted

Solution code:
from collections import deque
def main():
  _map, _input, _int = map, input, int
  n, q = _map(_int, _input().split())
  values = [0] * n
  links = [[] for _ in range(n)]
  for _ in range(n - 1):
    a, b = _map(_int, _input().split())
    if a >= b:
      return
    links[a - 1].append(b - 1)
    links[b - 1].append(a - 1)
  for _ in range(q):
    p, x = _map(_int, _input().split())
    values[p - 1] += x
  d = deque()
  d.append((0, -1))
  while len(d) != 0:
    i, p = d.popleft()
    for j in links[i]:
      if j == p:
        continue
      values[j] += values[i]
      d.append((j, i))
  print(*values)
main()

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10**6)

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

g = []
counter = []
ans = []

def dfs(cur, par, val):
  global counter, ans, g
  val += counter[cur]
  ans[cur] = val
  for e in g[cur]:
    if e == par:
      continue
    dfs(e, cur, val)

def main():
  global g, ans, counter
  N, Q = na()
  
  g = [[] for _ in range(N)]
  for _ in range(N - 1):
    a, b = na()
    g[a-1] += [b-1]
    g[b-1] += [a-1]

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

  ans = [0] * N
  dfs(0, -1, 0)
  print(*ans)

if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
from pprint import pprint
from collections import deque, defaultdict

import sys

# n, q = map(int, input().strip().split(" "))
n, q = map(int, sys.stdin.readline().strip().split(" "))
edges = [[] for _ in range(n)]
for _ in range(n-1):
    # a_i, b_i = map(int, input().strip().split(" "))
    a_i, b_i = map(int, sys.stdin.readline().strip().split(" "))
    edges[a_i-1].append(b_i-1)
    edges[b_i-1].append(a_i-1)

counter = [0] * n
p = [0] * n
for _ in range(q):
    # p_i, x_i = map(int, input().strip().split(" "))
    p_i, x_i = map(int, sys.stdin.readline().strip().split(" "))
    counter[p_i-1] += x_i


parents = deque()
parents.append(0)
visited = set()
while parents:
    parent = parents.popleft()
    if parent in visited:
        continue
    visited.add(parent)
    for child in edges[parent]:
        if child in visited:
            continue
        counter[child] += counter[parent]
        # print("child")
        # print(child, counter[child])
        parents.append(child)

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

Submission status: Accepted

Solution code:
from pprint import pprint
from collections import deque, defaultdict

n, q = map(int, input().strip().split(" "))
edges = [[] for _ in range(n)]
for _ in range(n-1):
    a_i, b_i = map(int, input().strip().split(" "))
    edges[a_i-1].append(b_i-1)
    edges[b_i-1].append(a_i-1)

counter = [0] * n
p = [0] * n
for _ in range(q):
    p_i, x_i = map(int, input().strip().split(" "))
    counter[p_i-1] += x_i


parents = deque()
parents.append(0)
visited = set()
while parents:
    parent = parents.popleft()
    if parent in visited:
        continue
    visited.add(parent)
    for child in edges[parent]:
        if child in visited:
            continue
        counter[child] += counter[parent]
        # print("child")
        # print(child, counter[child])
        parents.append(child)

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

Submission status: Accepted

Solution code:
from collections import deque
n,q = map(int,input().split())
g = [[] for _ in range(n+1)]
v = [0]*(n+1)
ans = [0]*(n+1)
for _ in range(n-1):
	a,b = map(int,input().split())
	g[a].append(b)
	g[b].append(a)
for _ in range(q):
	p,x = map(int,input().split())
	v[p] += x
alr = [False]*(n+1)
ans[1] = v[1]
stk = deque()
stk.append(1)
while stk:
	cur = stk.pop()
	alr[cur] = True
	for nxt in g[cur]:
		if not alr[nxt]:
			ans[nxt] = ans[cur] + v[nxt]
			stk.append(nxt)
print(*ans[1:])

Submission status: Accepted

Solution code:
from pprint import pprint
from collections import deque, defaultdict
 
n, q = list(map(int, input().strip().split(" ")))
# edges = defaultdict(set)
edges = [[] for _ in range(n)]
for _ in range(n-1):
    a_i, b_i = list(map(int, input().strip().split(" ")))
    edges[a_i-1].append(b_i-1)
    edges[b_i-1].append(a_i-1)
    # edges[a_i-1].add(b_i-1)
    # edges[b_i-1].add(a_i-1)
 
# p = defaultdict(int)
# counter = defaultdict(int)
counter = [0] * n
p = [0] * n
for _ in range(q):
    p_i, x_i = list(map(int, input().strip().split(" ")))
    # p[p_i-1] += x_i
    counter[p_i-1] += x_i
 
 
parents = deque()
# parents.append(0)
# parents = []
parents.append(0)
visited = set()
while parents:
    parent = parents.popleft()
    # parent = parents.pop()
    if parent in visited:
        continue
    visited.add(parent)
    # counter[parent] += p[parent]
    # print("parent")
    # print(parent, counter[parent])
    for child in edges[parent]:
        if child in visited:
            continue
        # if counter[child] != 0:
        #    continue
        counter[child] += counter[parent]
        # print("child")
        # print(child, counter[child])
        parents.append(child)
        # parents.add(child)
 
#print(" ".join(list(map(str, counter.values()))))
#print(" ".join(list(map(str, counter))))
print(*counter)

Submission status: Accepted

Solution code:
from pprint import pprint
from collections import deque

import sys

n, q = map(int, sys.stdin.readline().strip().split(" "))
edges = [[] for _ in range(n)]
for _ in range(n-1):
    a_i, b_i = map(int, sys.stdin.readline().strip().split(" "))
    edges[a_i-1].append(b_i-1)
    edges[b_i-1].append(a_i-1)

counter = [0] * n
p = [0] * n
for _ in range(q):
    p_i, x_i = map(int, sys.stdin.readline().strip().split(" "))
    counter[p_i-1] += x_i


parents = deque()
parents.append(0)
visited = set()
while parents:
    parent = parents.popleft()
    if parent in visited:
        continue
    visited.add(parent)
    for child in edges[parent]:
        if child in visited:
            continue
        counter[child] += counter[parent]
        parents.append(child)

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
 

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

T = [[]for i in range(N)]

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

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

# def dfs(x, p):
#     for j in T[x]:
#         if j == p:
#             continue
#         X[j] += X[x]
#         dfs(j, x)
def dfs(nownode,oya=-1):
    for nextnode in T[nownode]:
        if oya == nextnode:
            continue
        X[nextnode] += X[nownode]
        dfs(nextnode,nownode)

dfs(0, -1)

print(*X)

Submission status: Accepted

Solution code:
from collections import deque
n,q = map(int,input().split())
g = [[] for _ in range(n+1)]
v = [0]*(n+1)
ans = [0]*(n+1)
for _ in range(n-1):
	a,b = map(int,input().split())
	g[a].append(b)
	g[b].append(a)
for _ in range(q):
	p,x = map(int,input().split())
	v[p] += x
alr = [False]*(n+1)
ans[1] = v[1]
que = deque()
que.append(1)
while que:
	cur = que.popleft()
	alr[cur] = True
	for nxt in g[cur]:
		if not alr[nxt]:
			ans[nxt] = ans[cur] + v[nxt]
			que.append(nxt)
print(*ans[1:])

Submission status: Accepted

Solution code:
#D - Ki問題　maspyさん
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

# 遅延評価で加えてあげるだけ

N,Q = map(int,input().split())
AB = [[int(x) for x in input().split()] for _ in range(N-1)]
PX = [[int(x) for x in input().split()] for _ in range(Q)]

graph = [[] for _ in range(N+1)]
for a,b in AB:
    graph[a].append(b)
    graph[b].append(a)

value = [0] * (N+1)
for p,x in PX:
    value[p] += x

def dfs(v,parent,add):
    value[v] += add
    for x in graph[v]:
        if x == parent:
            continue
        dfs(x,v,value[v])

dfs(1,0,0)

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
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)]

es = [[] for i in range(N)]
for a,b in AB:
    a,b = a-1,b-1
    es[a].append(b)
    es[b].append(a)

xs = [0] * N
for p,x in PX:
    xs[p-1] += x

ans = [0] * N
ans[0] = xs[0]
visited = [0] * N
stack = [0]
while stack:
    v = stack.pop()
    visited[v] = 1
    for to in es[v]:
        if visited[to]: continue
        stack.append(to)
        ans[to] = ans[v] + xs[to]

print(*ans)

Submission status: Accepted

Solution code:
(n,q),*t=[map(int,t.split())for t in open(0)]
s=[0]
d=s*n
f=s+[1]*n
e=[[]for _ in d]
for t in t:
 a,b=t
 if~-n:n-=1;e[a-1]+=b-1,;e[b-1]+=a-1,
 else:d[a-1]+=b
while s:
 v=s.pop()
 for w in e[v]:
  if f[w]:d[w]+=d[v];s+=w,;f[w]=0
print(*d)

Submission status: Accepted

Solution code:
(n,q),*t=[map(int,t.split())for t in open(0)]
s=[0]
d=s*n
f=s+[1]*n
e=[[]for _ in d]
for t in t:
  a,b=t
  if~-n:
    n-=1
    e[a-1]+=b-1,
    e[b-1]+=a-1,
  else:d[a-1]+=b
while s:
  v=s.pop()
  for w in e[v]:
    if f[w]:
      d[w]+=d[v]
      s+=w,
      f[w]=0
print(*d)