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: Time Limit Exceeded

Solution code:
import copy

N,Q = map(int,input().split())
ki = [list(map(int,input().split())) for i in range(N-1)]
co = [list(map(int,input().split())) for i in range(Q)]
 
ki.sort()
#print(ki)
 
ver = [0 for i in range(N)]
 
for i in range(Q):
    ver[co[i][0]-1] += co[i][1]
 
ver2 = copy.deepcopy(ver)

#print(ver)
#print(ver2)
 
for i in range(N-1):
    if ver[ki[i][0]-1] == ver2[ki[i][0]-1] and ver[ki[i][1]-1] != ver2[ki[i][1]-1]:
        ver[ki[i][0]-1] += ver[ki[i][1]-1]
    else:
        ver[ki[i][1]-1] += ver[ki[i][0]-1]

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

Submission status: Time Limit Exceeded

Solution code:
from _collections import deque


def parser():
    while 1:
        data = list(input().split(' '))
        for number in data:
            if len(number) > 0:
                yield (number)


input_parser = parser()


def gw():
    global input_parser
    return next(input_parser)


def gi():
    data = gw()
    return int(data)


MOD = int(1e9 + 7)

import numpy
import scipy
from collections import deque
#https://atcoder.jp/contests/abc141/tasks/abc141_d
#D - Powerful Discount Tickets
"""
need to consider the case that ticket is not enough to lower everything
"""
N = gi()
Q = gi()
nbls = [[] for _ in range(N + 5)]
ps = [0] * (N + 5)
xs = [0] * (N + 5)

for _ in range(N - 1):
    a = gi()
    b = gi()
    nbls[a].append(b)
    nbls[b].append(a)

for _ in range(Q):
    p = gi()
    x = gi()
    xs[p] += x

q = deque()
q.append(1)

while len(q):
    v = q.pop()
    for u in nbls[v]:
        if (u == ps[v]):
            continue
        ps[u] = v
        xs[u] += xs[v]
        q.append(u)

for i in range(1, N + 1):
    if (i == N):
        print(xs[i])
    else:
        print("%d " % (xs[i]), end=" ")

Submission status: Time Limit Exceeded

Solution code:
from collections import deque #pypyでも使える
n,q=map(int,input().split())
oyako=[]
for i in range(n-1):
	ab=list(map(lambda x:int(x)-1,input().split()))
	#もっといい感じの書き方ないかな?
	oyako.append(ab)
nodes=[0]*n
for i in range(q):
	p,x=map(int,input().split())
	p-=1
	nodes[p]+=x
#oyakoを、親についての単調増加にしたい->デフォで先頭要素でのソートになるので安心
#oyako.sort()
#と思ったけどソートじゃ無理っぽい
#根から順に処理->bfs幅優先探索
que=deque([0])
color=[0]*n #全てのノードに対して、未探索の0を入れる
color[0]=0 #colorは親としての処理を終えたかどうかを入れる。終えたら1にする
while que: #qが空でないのはこう表現できる
	i=que.popleft()
	if color[i]==0:
		for ab in oyako:
			if ab[0]==i and color[ab[1]]==0:
				nodes[ab[1]]+=nodes[i]
				que.append(ab[1])
			elif ab[1]==i and color[ab[0]]==0:
				nodes[ab[0]]+=nodes[i]
				que.append(ab[0])
		color[i]=1

#綺麗にかけそうでこの書き方をしたけど大丈夫かな?
for node in nodes:
	print(node,end=' ')

Submission status: Time Limit Exceeded

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


N, Q = map(int, input().split())
G = [[] for _ in range(N)]
P = [0 for _ in range(N)]

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

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


def dfs(current, parent):
    for child in G[current]:
        if child == parent:
            continue
        P[child] += P[current]
        dfs(child, current)


dfs(0, -1)

print(' '.join([str(p) for p in P]))

Submission status: Time Limit Exceeded

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


N, Q = map(int, input().split())
G = defaultdict(set)
X = defaultdict(int)
P = defaultdict(int)

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

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


def dfs(p, x, parent):

    P[p] += x + X[p]
    for node in G[p]:
        if node == parent:
            continue
        dfs(node, x + X[p], p)


dfs(0, 0, -1)

print(' '.join([str(p) for p in P.values()]))

Submission status: Time Limit Exceeded

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


N, Q = map(int, input().split())
G = defaultdict(set)
X = [0 for _ in range(N)]
P = [0 for _ in range(N)]

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

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


def dfs(p, x, parent):

    P[p] += x + X[p]
    for node in G[p]:
        if node == parent:
            continue
        dfs(node, x + X[p], p)


dfs(0, 0, -1)

print(' '.join([str(p) for p in P]))

Submission status: Time Limit Exceeded

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


N, Q = map(int, input().split())
G = [[] for _ in range(N)]
X = [0 for _ in range(N)]
P = [0 for _ in range(N)]

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

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


def dfs(p, x, parent):

    P[p] += x + X[p]
    for node in G[p]:
        if node == parent:
            continue
        dfs(node, x + X[p], p)


dfs(0, 0, -1)

print(' '.join([str(p) for p in P]))

Submission status: Time Limit Exceeded

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

from collections import defaultdict
dic = defaultdict(int)
for _ in range(q):
   p,x = map(int,input().split())
   dic[p-1] += x

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

used = [0 for i in range(n)]
used[0] = 1
quu = [0]
while quu:
   k = quu.pop(0)
   for l in m[k]:
      if used[l] == 0:
         used[l] = 1
         quu.append(l)
         ans[l] = ans[k] + dic[l]

for i in ans:
   print(i)

Submission status: Time Limit Exceeded

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

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


ps = []
xs = []
for i in range(q):
    p,x = map(int,input().split())
    ps.append(p)
    xs.append(x)


graph = [[] for i in range(n+1)]
parent = [0 for i in range(n+1)]
root = 1
stack = [root]
for i in range(n-1):
    graph[e[i][0]].append(e[i][1])
    graph[e[i][1]].append(e[i][0])

order = []
while stack:
    x = stack.pop()
    order.append(x)
    for y in graph[x]:
        if parent[x] == y:
            continue
        parent[y] = x
        stack.append(y)

cnt = [0] * (n+1)
for i in range(q):
    cnt[ps[i]] += xs[i]

ans = [0] * (n+1)
for j in order:
    ans[j] = cnt[j] + ans[parent[j]]

print(*ans[1:],sep = " ")

Submission status: Time Limit Exceeded

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


def dfs(x, w):
    w += leaves[x]
    for nx in [e for e in edge[x] if V[e] == 0]:
        V[nx] = 1
        dfs(nx, w)
    leaves[x] = w


N, Q = map(int, input().split())
edge = [[] for _ in range(N)]
leaves = [0] * N
V = [0] * N

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

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

V[0] = 1
dfs(0, 0)
for i in range(N - 1):
    print(leaves[i], end=' ')
print(leaves[N - 1])

Submission status: Time Limit Exceeded

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


def dfs(x, w):
    w += leaves[x]
    for nx in [e for e in edge[x] if V[e] == 0]:
        V[nx] = 1
        dfs(nx, w)
    leaves[x] = w


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

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

leaves = [0] * N
V = [0] * N
V[0] = 1

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

dfs(0, 0)
for i in range(N - 1):
    print(leaves[i], end=' ')
print(leaves[N - 1])

Submission status: Time Limit Exceeded

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


def dfs(x, w):
    w += leaves[x]
    for nx in edge[x]:
        if V[nx] == 0:
            V[nx] = 1
            dfs(nx, w)
    leaves[x] = w


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

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

leaves = [0] * N
V = [0] * N
V[0] = 1

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

dfs(0, 0)
for i in range(N - 1):
    print(leaves[i], end=' ')
print(leaves[N - 1])

Submission status: Time Limit Exceeded

Solution code:
n, q = [int(_) for _ in input().split()]
w = {}
add = {}
seen = {}
ans_d = {}
for i in range(1, n + 1):
    w[i] = []
    seen[i] = 0
    add[i] = 0
    ans_d[i] = 0
for i in range(n - 1):
    a, b = [int(_) for _ in input().split()]
    w[a].append(b)
    w[b].append(a)
for i in range(q):
    p, x = [int(_) for _ in input().split()]
    add[p] += x

que = [1]
ans_d[1] = add[1]
seen[1] = 1
while len(que) != 0:
    v = que.pop()
    for node in w[v]:
        if seen[node] == 0:
            ans_d[node] = ans_d[v] + add[node]
            que.append(node)
            seen[node] = 1

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

Submission status: Time Limit Exceeded

Solution code:
import copy
import sys

sys.setrecursionlimit(10**8)

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

def dfs(v):
    seen[v] = True

    for i in graph[v]:
        if seen[i] == True:
            continue
        ans[i] += ans[v]
        dfs(i)

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

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

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

    ans[p] += x

seen = [False for i in range(N)]
dfs(0)

print(*ans)

Submission status: Time Limit Exceeded

Solution code:
import copy
import sys

sys.setrecursionlimit(10**8)

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

def dfs(v, d, p_list=[0]):
    seen[v] = True
    depth[v] = d
    parents_list[v] = copy.copy(p_list)
    for i in graph[v]:
        if seen[i] == True:
            continue
        p_list.append(i)
        dfs(i, d+1, p_list)
        p_list.pop()

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

seen = [False for i in range(N)]
depth = [0 for i in range(N)]
parents_list = [[] for i in range(N)]
dfs(0, 0)

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

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

    for j, parent in enumerate(parents_list):
        if p in parent:
            ans[j] += x

print(*ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(500*500) # default 1000
N, Q = map(int, input().strip().split())

# visited = [False for _ in range(N)]
# def dfs(v): # vertices & parent idx
#     visited[v]=True
#     for child in to[v]:
#         if visited[child]==True:
#             continue
#         ans[child]+=ans[v]
#         dfs(child)
def dfs(v,p=-1): # vertices & parent idx
    for child in to[v]:
        if child!=p:
          ans[child]+=ans[v]
          dfs(child,v)
        


to=[[] for j in range(N)] # N points
ans=[0]*N # N points

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

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(500*500) # default 1000
N, Q = map(int, input().strip().split())

# visited = [False for _ in range(N)]
# def dfs(v): # vertices & parent idx
#     visited[v]=True
#     for child in to[v]:
#         if visited[child]==True:
#             continue
#         ans[child]+=ans[v]
#         dfs(child)
def dfs(v,p=-1): # vertices & parent idx
    for child in to[v]:
        if child==p:
            continue
        ans[child]+=ans[v]
        dfs(child,v)
        


to=[[] for j in range(N)] # N points
ans=[0]*N # N points

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

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(500*500) # default 1000
N, Q = map(int, input().strip().split())
visited = [False for _ in range(N)]
def dfs(v): # vertices & parent idx
    visited[v]=True
    for child in to[v]:
        if visited[child]==True:
            continue
        ans[child]+=ans[v]
        dfs(child)
# def dfs(v,p=-1): # vertices & parent idx
#     for child in to[v]:
#         if child==p:
#             continue
#         ans[child]+=ans[v]
#         dfs(child,v)
        


to=[[] for j in range(N)] # N points
ans=[0]*N # N points

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

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

dfs(0)
for i in range(N):
    print(ans[i],end=' ')

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(500*500) # default 1000

def dfs(v,p=-1): # vertices & parent idx
    for child in to[v]:
        if child==p:
            continue
        ans[child]+=ans[v]
        # print('vertices=',v)
        # print('child=',child)
        # print('parent=',p)
        dfs(child,v)
        
N, Q = map(int, input().strip().split())

to=[[] for j in range(N)] # N points
ans=[0]*N # N points

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

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

dfs(0)
for i in range(N):
    print(ans[i],end=' ')

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(500*500) # default 1000



def dfs(v,p=-1): # vertices & parent idx
    lst=to[v] # children list
    for child in lst:
        if child==p:
            continue
        ans[child]+=ans[v]
        # print('vertices=',v)
        # print('child=',child)
        # print('parent=',p)
        dfs(child,v)
        
N, Q = map(int, input().strip().split())

to=[[] for j in range(N)] # N points
ans=[0]*N # N points

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

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

dfs(0)
for i in range(N):
    print(ans[i],end=' ')

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(500*500) # default 1000

class data():
    def __init__(self,N):
        self.to=[[] for j in range(N)] # N points
        self.c=[0]*N # N points

def dfs(v,p=-1): # vertices & parent idx
    lst=data.to[v] # children list
    for child in lst:
        if child==p:
            continue
        data.c[child]+=data.c[v]
        # print('vertices=',v)
        # print('child=',child)
        # print('parent=',p)
        dfs(child,v)
        
N, Q = map(int, input().strip().split())
data=data(N)
for i in range(N-1):
    a,b=map(int, input().strip().split())
    a-=1
    b-=1
    data.to[a].append(b)
    data.to[b].append(a)

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

dfs(0)
for i in range(N):
    print(data.c[i],end=' ')

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(500*500) # default 1000

class data():
    def __init__(self,N):
        self.to=[[] for j in range(N)] # N points
        self.c=[0]*N # N points
        self.x=[0]*N

def dfs(v,p=-1): # vertices & parent idx
    lst=data.to[v] # children list
    if p==-1:
        data.c[v]=data.x[v]
    else:
        data.c[v]=data.c[p]+data.x[v]
    
    for child in lst:
        if child==p:
            continue
        # print('vertices=',v)
        # print('child=',child)
        # print('parent=',p)
        dfs(child,v)
        
N, Q = map(int, input().strip().split())
data=data(N)
for i in range(N-1):
    a,b=map(int, input().strip().split())
    a-=1
    b-=1
    data.to[a].append(b)
    data.to[b].append(a)

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

dfs(0)
for i in range(N):
    print(data.c[i],end=' ')

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(500*500) # default 1000

class data():
    def __init__(self,N):
        self.to=[[] for j in range(N)] # N points
        self.c=[0]*N # N points
        self.x=[0]*N

def dfs(v,p=-1): # vertices & parent idx
    lst=data.to[v] # children list
    if p==-1:
        data.c[v]=data.x[v]
    else:
        data.c[v]=data.c[p]+data.x[v]
    
    for i,child in enumerate(lst):
        if child==p:
            continue
        # print('vertices=',v)
        # print('child=',child)
        # print('parent=',p)
        dfs(child,v)
        
N, Q = map(int, input().strip().split())
data=data(N)
for i in range(N-1):
    a,b=map(int, input().strip().split())
    a-=1
    b-=1
    data.to[a].append(b)
    data.to[b].append(a)

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

dfs(0)
for i in range(N):
    print(data.c[i],end=' ')

Submission status: Time Limit Exceeded

Solution code:
#AtCorder用　自動木取得コード

#１行目がノードの数、２行目以降が２つの数字でノードを繋ぐ辺を表すとき、使える

#変数
#node_n :ノードの数
#edge   :エッジを、入力の順番でリストとして提供
#【注意】ノードクラスのリストは関数で取り出さないと、連動して変わってしまう


#関数
#・getroot()で根を取り出す
#・getleaf()で葉を取り出す
#・childに子のノードクラスのリストが格納
#・parentに親のノードクラスが格納





import sys
sys.setrecursionlimit(1000000)

from collections import deque
#ノードクラス
class Node():
    def __init__(self):
        self.name=-1
        self.parent=-1
        self.child=[]
        self.counter=0
        
        
        
    #ノードに対する子供の数を取得
    def childnum(self):
        return len(self.child)

    

#木クラス
class Tree():
    
    
    #作成した瞬間、入力の数だけノードを作る。
    def __init__(self,n):
        self.tree=[]
        self.node_n=n
        for i in range(self.node_n):
            a=Node()
            a.name=i
            self.tree.append(a)
        self.edge=[]
        for i in range(self.node_n-1):
            self.edge.append([int(j) for j in input().split()])
        copyedge=sorted(self.edge)
        checkedge=deque()
        for edge in copyedge:
            first=self.tree[edge[0]-1]
            second=self.tree[edge[1]-1]
            if first.parent!=-1 or first.name==0:
                first.child.append(second)
                second.parent=first
            elif second.parent!=-1:
                second.child.append(first)
                first.parent=second
            else:
                checkedge.append(edge)
                
        while checkedge:
            edge=checkedge.popleft()
            first=self.tree[edge[0]-1]
            second=self.tree[edge[1]-1]
            if first.parent!=-1:
                first.child.append(second)
                second.parent=first
            elif second.parent!=-1:
                second.child.append(first)
                first.parent=second
            else:
                checkedge.append(edge)
     
    #根ノードを取得
    def getroot(self):
        return self.tree[0]
    
    #葉ノードのリストを取得
    def getleaf(self):
        leaf=[]
        for i in self.tree:
            if i.child==[]:
                leaf.append(i)
        return leaf
    
    
    #全ノードリストを取得
    def gettree(self):
        return self.tree[:]

    
n,q=[int(i) for i in input().split()]
tree=Tree(n)
nodes=tree.tree
opelist=[]
for i in range(q):
    opelist.append([int(j) for j in input().split()])



for ope in opelist:
    nodes[ope[0]-1].counter+=ope[1]

    

node=tree.getroot()

def dpm(node):
    children=node.child
    if children!=[]:
        for child in children:
            child.counter+=node.counter
            dpm(child)
            
dpm(node)

for i in range(n):
    if i==n-1:
        print(nodes[i].counter)
    else:
        print(nodes[i].counter,end=(" "))

Submission status: Time Limit Exceeded

Solution code:
#AtCorder用　自動木取得コード

#１行目がノードの数、２行目以降が２つの数字でノードを繋ぐ辺を表すとき、使える

#変数
#node_n :ノードの数
#edge   :エッジを、入力の順番でリストとして提供
#【注意】ノードクラスのリストは関数で取り出さないと、連動して変わってしまう


#関数
#・getroot()で根を取り出す
#・getleaf()で葉を取り出す
#・childに子のノードクラスのリストが格納
#・parentに親のノードクラスが格納






from collections import deque
#ノードクラス
class Node():
    def __init__(self):
        self.name=-1
        self.parent=-1
        self.child=[]
        self.counter=0
        
        
        
    #ノードに対する子供の数を取得
    def childnum(self):
        return len(self.child)

    

#木クラス
class Tree():
    
    
    #作成した瞬間、入力の数だけノードを作る。
    def __init__(self,n):
        self.tree=[]
        self.node_n=n
        for i in range(self.node_n):
            a=Node()
            a.name=i
            self.tree.append(a)
        self.edge=[]
        for i in range(self.node_n-1):
            self.edge.append([int(j) for j in input().split()])
        copyedge=sorted(self.edge)
        checkedge=deque()
        for edge in copyedge:
            first=self.tree[edge[0]-1]
            second=self.tree[edge[1]-1]
            if first.parent!=-1 or first.name==0:
                first.child.append(second)
                second.parent=first
            elif second.parent!=-1:
                second.child.append(first)
                first.parent=second
            else:
                checkedge.append(edge)
                
        while checkedge:
            edge=checkedge.popleft()
            first=self.tree[edge[0]-1]
            second=self.tree[edge[1]-1]
            if first.parent!=-1:
                first.child.append(second)
                second.parent=first
            elif second.parent!=-1:
                second.child.append(first)
                first.parent=second
            else:
                checkedge.append(edge)
     
    #根ノードを取得
    def getroot(self):
        return self.tree[0]
    
    #葉ノードのリストを取得
    def getleaf(self):
        leaf=[]
        for i in self.tree:
            if i.child==[]:
                leaf.append(i)
        return leaf
    
    
    #全ノードリストを取得
    def gettree(self):
        return self.tree[:]

    
n,q=[int(i) for i in input().split()]
tree=Tree(n)
nodes=tree.tree
opelist=[]
for i in range(q):
    opelist.append([int(j) for j in input().split()])



for ope in opelist:
    nodes[ope[0]-1].counter+=ope[1]

    

node=tree.getroot()

def dpm(node):
    children=node.child
    if children!=[]:
        for child in children:
            child.counter+=node.counter
            dpm(child)
            
dpm(node)

for i in range(n):
    if i==n-1:
        print(nodes[i].counter)
    else:
        print(nodes[i].counter,end=(" "))

Submission status: Time Limit Exceeded

Solution code:
#AtCorder用　自動木取得コード

#１行目がノードの数、２行目以降が２つの数字でノードを繋ぐ辺を表すとき、使える

#変数
#node_n :ノードの数
#edge   :エッジを、入力の順番でリストとして提供
#【注意】ノードクラスのリストは関数で取り出さないと、連動して変わってしまう


#関数
#・getroot()で根を取り出す
#・getleaf()で葉を取り出す
#・childに子のノードクラスのリストが格納
#・parentに親のノードクラスが格納




from collections import deque

#ノードクラス
class Node():
    def __init__(self):
        self.name=-1
        self.parent=-1
        self.child=[]
        self.counter=0
        
        
        
        
    #ノードに対する子供の数を取得
    def childnum(self):
        return len(self.child)

    

#木クラス
class Tree():
    
    
    #作成した瞬間、入力の数だけノードを作る。
    def __init__(self,n):
        self.tree=[]
        self.node_n=n
        for i in range(self.node_n):
            a=Node()
            a.name=i
            self.tree.append(a)
        self.edge=[]
        for i in range(self.node_n-1):
            self.edge.append([int(j) for j in input().split()])
        checkedge=deque()
        for edge in self.edge:
            first=self.tree[edge[0]-1]
            second=self.tree[edge[1]-1]
            if first.parent!=-1 or first.name==0:
                first.child.append(second)
                second.parent=first
            elif second.parent!=-1:
                second.child.append(first)
                first.parent=second
            else:
                checkedge.append(edge)
        while checkedge:
            edge=checkedge.popleft()
            first=self.tree[edge[0]-1]
            second=self.tree[edge[1]-1]
            if first.parent!=-1 or first.name==0:
                first.child.append(second)
                second.parent=first
            elif second.parent!=-1:
                second.child.append(first)
                first.parent=second
            else:
                checkedge.append(edge)
       
     
    #根ノードを取得
    def getroot(self):
        return self.tree[0]
    
    #葉ノードのリストを取得
    def getleaf(self):
        leaf=[]
        for i in self.tree:
            if i.child==[]:
                leaf.append(i)
        return leaf
    
    
    #全ノードリストを取得
    def gettree(self):
        return self.tree[:]
    
    
n,q=[int(i) for i in input().split()]
tree=Tree(n)
nodes=tree.tree
opelist=[]
for i in range(q):
    opelist.append([int(j) for j in input().split()])



for ope in opelist:
    nodes[ope[0]-1].counter+=ope[1]

    

node=tree.getroot()

def dpm(node):
    children=node.child
    if children!=[]:
        for child in children:
            child.counter+=node.counter
            dpm(child)
            
dpm(node)

for i in range(n):
    if i==n-1:
        print(nodes[i].counter)
    else:
        print(nodes[i].counter,end=(" "))

Submission status: Time Limit Exceeded

Solution code:
#AtCorder用　自動木取得コード

#１行目がノードの数、２行目以降が２つの数字でノードを繋ぐ辺を表すとき、使える

#変数
#node_n :ノードの数
#edge   :エッジを、入力の順番でリストとして提供
#【注意】ノードクラスのリストは関数で取り出さないと、連動して変わってしまう


#関数
#・getroot()で根を取り出す
#・getleaf()で葉を取り出す
#・childに子のノードクラスのリストが格納
#・parentに親のノードクラスが格納






#ノードクラス
class Node():
    def __init__(self):
        self.name=-1
        self.parent=-1
        self.child=[]
        self.counter=0
        
        
        
        
    #ノードに対する子供の数を取得
    def childnum(self):
        return len(self.child)

    

#木クラス
class Tree():
    
    
    #作成した瞬間、入力の数だけノードを作る。
    def __init__(self,n):
        self.tree=[]
        self.node_n=n
        for i in range(self.node_n):
            a=Node()
            a.name=i
            self.tree.append(a)
        self.edge=[]
        for i in range(self.node_n-1):
            self.edge.append([int(j) for j in input().split()])
        checkedge=self.edge[::-1]
        while checkedge:
            edge=checkedge.pop()
            first=self.tree[edge[0]-1]
            second=self.tree[edge[1]-1]
            if first.parent!=-1 or first.name==0:
                first.child.append(second)
                second.parent=first
            elif second.parent!=-1:
                second.child.append(first)
                first.parent=second
            else:
                checkedge=[edge]+checkedge
       
     
    #根ノードを取得
    def getroot(self):
        return self.tree[0]
    
    #葉ノードのリストを取得
    def getleaf(self):
        leaf=[]
        for i in self.tree:
            if i.child==[]:
                leaf.append(i)
        return leaf
    
    
    #全ノードリストを取得
    def gettree(self):
        return self.tree[:]
    
    
n,q=[int(i) for i in input().split()]
tree=Tree(n)
nodes=tree.tree
opelist=[]
for i in range(q):
    opelist.append([int(j) for j in input().split()])



for ope in opelist:
    nodes[ope[0]-1].counter+=ope[1]

    

node=tree.getroot()

def dpm(node):
    children=node.child
    if children!=[]:
        for child in children:
            child.counter+=node.counter
            dpm(child)
            
dpm(node)

for i in range(n):
    if i==n-1:
        print(nodes[i].counter)
    else:
        print(nodes[i].counter,end=(" "))

Submission status: Time Limit Exceeded

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

graph = [[] for _ in range(N + 1)]
for A, B in AB:
  graph[A].append(B)
  graph[B].append(A)
#print("graph:", graph)
  
X = [0] * (N + 1)
for p, x in PX:
  X[p] += x
#print("X:", X)

stack = [1]
check = [0] * (N + 1)
check[1] = 1
cnt = [0] * (N + 1)
cnt[1] = X[1]

while stack:
  s = stack.pop()
  for g in graph[s]:
    if check[g] == 0:
      check[g] = 1
      cnt[g] = cnt[s] + X[g]
      stack.append(g)
print(*cnt[1::])

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(200000)

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

Adj_dict = {}
for i in range(n):
    new = {i:[]}
    Adj_dict.update(new)
for _ in range(n-1):
    a,b = map(int, input().split())
    Adj_dict[a-1].append(b-1)
    Adj_dict[b-1].append(a-1)

PX_dict = {}
for _ in range(q):
    p,x = map(int, input().split())
    if p-1 in PX_dict.keys():
        PX_dict[p-1] += x
    else:
        new = {p-1:x}
        PX_dict.update(new)

Visited = [False for _ in range(n)]
Ans = [0 for _ in range(n)]

def tree_counter(Adj=Adj_dict, PX=PX_dict, start=0, counter=0, Visited=Visited, Ans=Ans):
    
    # 終端処理
    if Visited[start] == True:
        return
    
    # Visit処理
    Visited[start] = True
    if start in PX.keys():
        counter += PX[start]
    Ans[start] = str(counter)

    for node in Adj[start]:
        if Visited[node] == False:
            tree_counter(Adj_dict, PX_dict, node, counter, Visited, Ans)
    
    return

tree_counter()
print(' '.join(Ans))