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

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

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

def rec(node, parent):
    for i in root[node]:
        if i == parent:
            continue
        cnt[i] += cnt[node]
        rec(i, node)

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

Submission status: Accepted

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

from collections import defaultdict, Counter, deque
from operator import itemgetter
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)
def inpl(): return list(map(int, input().split()))

N, Q = inpl()
G = [[] for _ in range(N)]

for _ in range(N-1):
    a, b = inpl()
    G[a-1].append(b-1)
    G[b-1].append(a-1)

S = [0]*N
for _ in range(Q):
    x, d = inpl()
    S[x-1] += d

searched = [0]*N
searched[0] = True
Q = deque([0])

while Q:
    p = Q.popleft()
    for q in G[p]:
        if searched[q]:
            continue
        searched[q] = True
        S[q] += S[p]
        Q.append(q)

print(*S)

Submission status: Accepted

Solution code:
# 解説動画から累積和ポイント。 
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
N,Q = map(int,input().split())
ABList = [list(map(int,list(input().split()))) for i in range(N-1)]  
PXList = [list(map(int,list(input().split()))) for i in range(Q)]  
 
# N+1 にしているのは、dfs関数でparentsを使う時に合わせるため 
graph=[[] for _ in range(N+1)]
values=[0]*(N+1)
 
for a,b in ABList:
    graph[a].append(b)
    graph[b].append(a)
    # aとbを入れ替えて
    # graphは例１の時、[[], [2], [1, 3, 4], [2], [2]] になる
    # 頂点がどことつながっているか 
for p,x in PXList:
    values[p]+=x
    # p をキーにしているのでNの昇順ｘにしている
    # 例１であれば[0, 100, 10, 1, 0]　累積和する前の値をもつ
 
def dfs(x,parent,add):
    # 累積和をvaluesに計算していく
    values[x]+=add
    for i in graph[x]:
        # continueはループの残りを飛ばして次の反復へ
        # 親と子判定
        if i==parent:
            continue
        dfs(i,x,values[x])
 
dfs(1,0,0)
 
print(' '.join(map(str,values[1:])))
# 難しい。graph[x]の使い方の理解がまだまだ

Submission status: Accepted

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

def main():
    N, Q = map(int, input().split())
    # edges = [None]*N
    edges = [[] for _ in range(N)]
    # edges[0] = 0
    # edges[0].append = 0
    for _ in range(N-1):
        a, b = map(int, input().split())
        edges[b-1].append(a-1)
        edges[a-1].append(b-1)

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

    parent_nodes = deque()
    parent_nodes.append(0)
    visited_nodes = set()
    while parent_nodes:
        parent = parent_nodes.popleft()
        if parent in visited_nodes:
            continue
        visited_nodes.add(parent)
        for child in edges[parent]:
            if child in visited_nodes:
                continue
            counts[child] += counts[parent]
            parent_nodes.append(child)

    print(' '.join(list(map(str, counts))))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(200005)
n, q = map(int, input().split())

to = [[] for i in range(n+1)]


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

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


def down_tree(index, parent):
    for i in to[index]:
        if i == parent:
            continue
        score[i] += score[index]
        down_tree(i, index)



down_tree(1, 1)

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

Submission status: Accepted

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

ct = [0] * (n+1)
o = [0] * (n+1)
g = [[] for _ in range(n+1)]

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

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

todo = [1]
seen = [False] * (n+1)
while todo:
  p = todo.pop(-1)
  ct[p] += o[p]
  seen[p] = True
  for i in g[p]:
    if seen[i]:
      ct[p] += ct[i]
    else:
      todo.append(i)

print(*ct[1:])

Submission status: Accepted

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

N,Q = map(int,input().split())
to = [[] for _ in range(N+1)]
ans = [0 for _ in range(N+1)]

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

def dfs(v, p):
    for u in to[v]:
        if u == p:
            continue
        ans[u] += ans[v]
        dfs(u, v)
dfs(1, -1)
print(*ans[1:])

Submission status: Accepted

Solution code:

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

ct = [0] * (n+1)
o = [0] * (n+1)
g = [[] for _ in range(n+1)]

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

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

todo = [1]
seen = [False] * (n+1)
while todo:
  p = todo.pop(-1)
  ct[p] += o[p]
  seen[p] = True
  for i in g[p]:
    if seen[i]:
      ct[p] += ct[i]
    else:
      todo.append(i)

print(*ct[1:])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)
 
def dfs(now, prev):
    ans[now]+=(h[now]+ans[prev])
    # 今いる頂点から行ける頂点を順に next に入れてループ
    for next in g[now]:
        if next != prev:
            dfs(next, now)
 
 
n, q = map(int, input().split())
g = [[] * n for i in range(n)]
for i in range(n-1):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    g[u].append(v)
    g[v].append(u)
 
h=[0]*n
for i in range(q):
    u, v = map(int, input().split())
    u -= 1
    h[u]+=v
 
ans=[0]*n
dfs(0,0)
 
print(' '.join(map(str, ans)))

Submission status: Accepted

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

def dfs(now, prev):
    ans[now]+=(h[now]+ans[prev])
    # 今いる頂点から行ける頂点を順に next に入れてループ
    for next in g[now]:
        if next != prev:
            if memo[next]==True:
                # 過去に訪れていれば終わらせる
                return False
            else:
                memo[next] = True
                dfs(next, now)
 
#木構造の取り込み 
n, q = map(int, input().split())
g = [[] * n for i in range(n)]
for i in range(n-1):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    g[u].append(v)
    g[v].append(u)
 
#操作の取り込み
h=[0]*n
for i in range(q):
    u, v = map(int, input().split())
    u -= 1
    h[u]+=v
 
#初期のカウンター
ans=[0]*n
memo = [False for i in range(n)]
 
#DFSでカウンターを動かす
dfs(0,0)
 
print(' '.join(map(str, ans)))

Submission status: Accepted

Solution code:
from collections import deque
N, Q = map(int, input().split())
edges = [list(map(int, input().split())) for _ in range(N-1)]
operations = [list(map(int, input().split())) for _ in range(Q)]

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

for edge in edges:
    a = edge[0]
    b = edge[1]
    edge_map[a-1].append(b-1)
    edge_map[b-1].append(a-1)


counters = [0]*N

for operation in operations:
    p = operation[0]
    x = operation[1]
    counters[p-1] += x


res_list = [counters[i] for i in range(N)]
calculated = [False for i in range(N)]

target = [0]
while len(target) > 0:
    t = target.pop()
    calculated[t] = True
    for child in edge_map[t]:
        if calculated[child]:
            continue
        target.append(child)
        res_list[child] += res_list[t]

print(*res_list)

Submission status: Accepted

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

ct = [0] * (n + 1)
e = [[] for _ in range(n + 1)]

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

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

target = [1]
visited = [0] * (n + 1)
while len(target):
    t = target.pop()
    visited[t] = 1
    ct[t] += qs[t]
    for nt in e[t]:
        if visited[nt] == 0:
            target.append(nt)
            ct[nt] += ct[t]

print(*ct[1:])

Submission status: Accepted

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

value = [0 for i in range(n+1)]
for p, x in px:
    value[p] += x

stack = [1]
flag = [False]*(n+1)
while stack:
    v = stack.pop()
    flag[v] = True
    for e in l[v]:
        if flag[e]:
            continue
        value[e] += value[v]
        stack.append(e)
        
print(*value[1:])

Submission status: Accepted

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

ct = [0] * (n + 1)
e = [[] for _ in range(n + 1)]

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

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

target = [1]
visited = set()
while len(target):
    t = target.pop()
    visited.add(t)
    ct[t] += qs[t]
    for nt in e[t]:
        if nt not in visited:
            target.append(nt)
            ct[nt] += ct[t]

print(*ct[1:])

Submission status: Accepted

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


N,Q = map(int,input().split())
trees = [[] for _ in range(N+1)]
values = [0 for _ in range(N+1)]

for _ in range(N-1):
  parent,child = map(int,input().split())
  trees[parent].append(child)
  trees[child].append(parent)

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

def recursive_func(i,parent):
  for child in trees[i]:
    if child == parent:
      continue
    values[child] += values[i]
    recursive_func(child,i)

recursive_func(1,-1)
print(*values[1:])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
n, q = map(int, input().split())

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

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

def dfs2(i, parent):
    for j in trees[i]:
        if j == parent: continue
        values[j] += values[i]
        dfs2(j, i)

dfs2(1, -1)
print(*values[1:])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)
 
def dfs(now, prev):
    ans[now]+=(h[now]+ans[prev])
    # 今いる頂点から行ける頂点を順に next に入れてループ
    for next in g[now]:
      	if next == prev:
        	continue
      	else:
          dfs(next, now)
 
#木構造の取り込み 
n, q = map(int, input().split())
g = [[] for _ in range(n)]
for i in range(n-1):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    g[u].append(v)
    g[v].append(u)

#操作の取り込み
h=[0]*n
for i in range(q):
    u, v = map(int, input().split())
    u -= 1
    h[u]+=v

#初期のカウンター
ans=[0]*n

#DFSでカウンターを動かす
dfs(0,0)
 
print(' '.join(map(str, ans)))

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(" "))
    p[p_i-1] += x_i
    # counter[p_i-1] += x_i
 
 
parents = deque()
parents.append(0)
visited = set()
while parents:
    parent = parents.popleft()
    if parent in visited:
        continue
    counter[parent] += p[parent]
    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:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
n, q = map(int, input().split())

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

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

def dfs(i, parent):
    for j in trees[i]:
        if j == parent: continue
        values[j] += values[i]
        dfs(j, i)

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
n, q = map(int, input().split())

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

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

def dfs2(i, parent):
    for j in trees[i]:
        if j == parent: continue
        values[j] += values[i]
        dfs2(j, i)

dfs2(0, -1)
print(*values)

Submission status: Accepted

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


N,Q=map(int,input().split())
EDGE=[list(map(int,input().split())) for i in range(N-1)]
PLUS=[list(map(int,input().split())) for i in range(Q)]

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

ELIST=[[] for i in range(N+1)]

for x,y in EDGE:
    ELIST[x].append(y)
    ELIST[y].append(x)
#print(ELIST)

from collections import deque
Q=deque([1])

USED=[0]*(N+1)
USED[1]=1
#USED = [0, 1, 0, 0, 0] Ex1
#SCORE = [0, 100, 10, 1, 0] Ex1
#ELIST = [[], [2], [1, 3, 4], [2], [2]] Ex1

while Q:
    x=Q.pop()

    for to in ELIST[x]:
        if USED[to]==0:
            USED[to]=1
            SCORE[to]+=SCORE[x]
            Q.append(to)

print(*SCORE[1:])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
n, q = map(int, input().split())

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

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

def dfs2(i, parent):
    for j in trees[i]:
        if j == parent: continue
        values[j] += values[i]
        dfs2(j, i)

dfs2(1, -1)
print(*values[1:])

Submission status: Accepted

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

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

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

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

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

def dfs(i, p):
  for c in nodes[i]:
    if c != p:
      values[c] += values[i]
      dfs(c, i)

dfs(0, None)
print(*values)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
n, q = map(int, input().split())

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

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

def dfs2(i, parent):
    for j in trees[i]:
        if j == parent: continue
        values[j] += values[i]
        dfs2(j, i)

dfs2(1, -1)
print(*values[1:])

Submission status: Accepted

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

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

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

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

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)]
c=[[] for i in range(n)]
for i in range(n-1):
  c[l[i][0]-1].append(l[i][1]-1)
  c[l[i][1]-1].append(l[i][0]-1)

l2=[list(map(int,input().split())) for i in range(q)]
L4=[0]*n
for i in range(q):
  L4[l2[i][0]-1]+=l2[i][1]
ans=[0]*n
ans[0]=L4[0]

L=[0]
L2=[]
L22=[-1]*n
L3=[]
while len(L2)!=n and len(L)!=0:
  for j in range(len(L)):
    x=L[j]
    L22[x]=1
    for k in range(len(c[x])):
      if L22[c[x][k]]==-1:
        ans[c[x][k]]=ans[x]+L4[c[x][k]]
        L3.append(c[x][k])
  L=L3
  L3=[]
for i in range(n):
  print(ans[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(1000000)
n, q = map(int, input().split())
 
ki = [[] for i in range(n + 1)]
for i in range(n - 1):
    a, b = map(int, input().split())
    ki[a].append(b)
    ki[b].append(a)
# print(ki)
 
cnt = [0] * (n + 1)
for i in range(q):
    p, x = map(int, input().split())
    cnt[p] += x
 
 
# print(cnt)
 
 
def d(y, parent):
    for i in ki[y]:
        if i == parent:
            continue
        cnt[i] += cnt[y]
        d(i, y)
 
 
d(1, -1)
print(*cnt[1:])

Submission status: Accepted

Solution code:
import sys
入力 = sys.stdin.readline
範囲, 出力 = range, print
真, 偽 = True, False
何もしない = None
一行に複数個の入力 = lambda:map(int, 入力().split())
頂点の数, 操作回数 = 一行に複数個の入力()
辺 = [[] for _ in 範囲(頂点の数)]
カウンター = [0] * 頂点の数
辺の数 = 頂点の数-1
for _ in 範囲(辺の数):
    頂点1, 頂点2 = 一行に複数個の入力()
    頂点1 -= 1
    頂点2 -= 1
    辺[頂点1] += 頂点2,
    辺[頂点2] += 頂点1,
for _ in 範囲(操作回数):
    頂点, 足す値 = 一行に複数個の入力()
    頂点 -= 1
    カウンター[頂点] += 足す値
到達済み = [偽] * 頂点の数
親 = 0
到達済み[親] = 真
スタック = [親]
while スタック:
    親 = スタック.pop()
    for 子 in 辺[親]:
        if 到達済み[子]:
            何もしない
        else:
            到達済み[子] = 真
            カウンター[子] += カウンター[親]
            スタック += 子,
出力(*カウンター)

Submission status: Accepted

Solution code:
MAX = 200005
G = [[] for i in range(MAX)]
adds = [0] * MAX
ans = [0] * MAX

# def dfs(c, p, count):
#     count += adds[c]
#     ans[c] += count
#     for i in range(len(G[c])):
#         if (G[c][i] != p):
#             dfs(G[c][i], c, count)

n, q = map(int, input().split())
for i in range(n - 1):
    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
    adds[p] += x

# dfs(0, -1, 0)
stack = [(0, -1, adds[0])]
while len(stack) != 0:
    cur, par, count = stack.pop()
    ans[cur] += count
    for i in range(len(G[cur])):
        if G[cur][i] != par:
            stack.append((G[cur][i], cur, count + adds[G[cur][i]]))
            
for i in range(n):
    print(ans[i])

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

Q = [0]

while Q:
    current = Q.pop()

    for i in M[current]:
        ans[i] += ans[current]
        M[i].remove(current)

    Q += M[current]

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

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)
  connection[l[i][1]-1].append(l[i][0]-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=[]
L22=[-1]*n
L3=[]
while len(L2)!=n and len(L)!=0:
  for j in range(len(L)):
    L22[L[j]]=1
    for k in range(len(connection[L[j]])):
      if L22[connection[L[j]][k]]==-1:
        distance[connection[L[j]][k]]=distance[L[j]]+L4[connection[L[j]][k]]
        L3.append(connection[L[j]][k])
  L=L3
  L3=[]
for i in range(len(distance)):
  print(distance[i])

Submission status: Accepted

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

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

xs = [0]*N
for _ in range(Q):
    p, x = map(int, input().split())
    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:
from sys import stdin,setrecursionlimit
input = stdin.readline
setrecursionlimit(1000000) 

N, Q = map(int, input().split())
T = [[] for _ in range(2 * (10 ** 5))]
for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    T[a].append(b)
    T[b].append(a)

d = [0] * N

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

def dfs(u, v):
    global d
    for p in T[u]:
        if p == v:
            continue
        d[p] += d[u]
        dfs(p, u)

dfs(0, -1)

for v in d:
    print(v)

Submission status: Accepted

Solution code:
from collections import deque

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

cnt = [0] * N

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

ans_list = [0] * N

dq = deque()
dq.append((0,-1,0))

while dq:
    v, pv, res = dq.popleft()
    res += cnt[v]
    ans_list[v] = res
    for nv in ad[v]:
        if nv == pv:
            continue
        dq.append((nv, v, res))

print(*ans_list)

Submission status: Accepted

Solution code:
N, T = map(int, input().split())
X = [[] for i in range(N)]
for i in range(N-1):
    x, y = map(int, input().split())
    X[x-1].append(y-1)
    X[y-1].append(x-1)

P = [-1] * N
Q = [0]
while Q:
    i = Q.pop()
    for a in X[i][::-1]:
        if a != P[i]:
            P[a] = i
            X[a].remove(i)
            Q.append(a)

C = [[] for i in range(N)]
for i in range(1, N):
    C[P[i]].append(i)
CT = [0] * N
XX = []
i = 0
while i >= 0:
    if CT[i] >= len(C[i]):
        XX.append(i)
        i = P[i]
    else:
        CT[i], i = CT[i] + 1, C[i][CT[i]]

A = [0] * N
for _ in range(T):
    p, x = map(int, input().split())
    A[p-1] += x

for i in XX[::-1]:
    if i: A[i] += A[P[i]]

print(*A)

Submission status: Accepted

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

N,M = map(int,input().split())
to = [[] for i in range(N)]
for i in range(N-1) :
    u,v = map(int,input().split())
    u -= 1
    v -= 1
    to[u].append(v)
    to[v].append(u)

ans = [0]*N

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

q = deque([0])
par = [-1]*N
while q :
    u = q.popleft()
    for v in to[u] :
        if v == par[u] :
            continue
        ans[v] += ans[u]
        par[v] = u
        q.append(v)
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)]
for i in range(N-1):
    a,b=map(int,input().split())
    L[a].append(b)
    L[b].append(a)
    
S=[0 for i in range(N+1)]
for i in range(Q):
    p,x=map(int,input().split())
    S[p]+=x
    
ANS=[-1 for i in range(N+1)]
ANS[1]=S[1]
l=[]
for i in L[1]:
    l.append([i,1,S[1]])
    
for i in range(N-1):
    X=l[i][0]
    Y=l[i][1]
    Z=l[i][2]
    ANS[X]=Z+S[X]
    for j in L[X]:
        if ANS[j]<0:
            l.append([j,X,ANS[X]])
print(*ANS[1:])

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations
import sys
import bisect
import string
sys.setrecursionlimit(10**6)
def SI():
    return input().split()
def MI():
    return map(int,input().split())
def I():
    return int(input())
def LI():
    return [int(i) for i in input().split()]
YN=['Yes','No']
mo=10**9+7

n,q=MI()
v=[0]*n
c=[0]*n
g=[[] for i in range(n)]
for i in range(n-1):
    a,b=MI()
    a-=1
    b-=1
    g[a].append(b)
    g[b].append(a)

for i in range(q):
    p,x=MI()
    c[p-1]+=x

#print(c)


def bfs(x):
    p=deque()
    p.append(x)
    while p:
        cur=p.popleft()
        v[cur]=1
        for i in g[cur]:
            if v[i]==0:
                p.append(i)
                c[i]+=c[cur]
bfs(0)

print(*c)

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

Q = [0]

while Q:
    current = Q.pop()

    for i in M[current]:
        ans[i] += ans[current]
        M[i].remove(current)
    
    Q += M[current]

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

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

Q = [0]

while Q:
    current = Q.pop()

    for i in M[current]:
        ans[i] += ans[current]
        M[i].remove(current)
        Q.append(i)

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

Submission status: Accepted

Solution code:
import sys
from collections import deque

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

Q = deque([0])

while Q:
    current = Q.pop()

    for i in M[current]:
        ans[i] += ans[current]
        M[i].remove(current)
        Q.append(i)

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
n,q=map(int,input().split())
edge=[[] for i in range(n)]
Chk=[False]*n
for i in range(n-1):
  a,b=map(int,input().split())
  edge[a-1]+=[b-1]
  edge[b-1]+=[a-1]
Ans=[0]*n
for i in range(q):
  p,x=map(int,input().split())
  Ans[p-1]+=x
Stack=[0]
Chk[0]=True
while Stack:
  c=Stack.pop(-1)
  ad=Ans[c]
  for ob in edge[c]:
    if Chk[ob]:
      continue
    else:
      Ans[ob]+=ad
      Stack+=[ob]
      Chk[ob]=True
print(*Ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000) 
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:
import sys
from collections import deque

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

Q = deque([0])

while Q:
    current = Q.popleft()

    for i in M[current]:
        ans[i] += ans[current]
        M[i].remove(current)
        Q.append(i)

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