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 sys
sys.setrecursionlimit(10**8)

def dfs(v):
  for u in g[v]:
    if checked[u]==1:
      continue
    checked[u]=1
    cnt[u]+=cnt[v]
    dfs(u)

n,q=map(int,input().split())
cnt=[0]*(n+1)
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)
for _ in range(q):
  v,val=map(int,input().split())
  cnt[v]+=val
checked=[0]*(n+1)
checked[1]=1
dfs(1)
print(*cnt[1:])

Submission status: Time Limit Exceeded

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

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

def dfs(x, p):
    for j in range(len(T[x])):
        if T[x][j] == p:
            continue
        ans[T[x][j]] += ans[x]
        dfs(T[x][j], x)

dfs(0, -1)

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

Submission status: Time Limit Exceeded

Solution code:
n, q = map(int, input().split())
a = []
b = []
hens = []
for i in range (n-1):
  t_a, t_b = map(int, input().split())
  a.append(t_a-1)
  b.append(t_b-1)
  hens.append([t_a-1, t_b-1])
p = []
x = []
for i in range (q):
  t_p, t_x = map(int, input().split())
  p.append(t_p-1)
  x.append(t_x)
c = [0 for i in range(n)]
tree = [[None, [], False] for i in range(n)]
tree[0][2] = True

while(len(hens) >= 1):
  for hen in hens[:]:
    if tree[hen[0]][2] == True:
      tree[hen[0]][1].append(hen[1])
      tree[hen[1]][0] = hen[0]
      tree[hen[1]][2] = True
    elif tree[hen[1]][2] == True:
      tree[hen[1]][1].append(hen[0])
      tree[hen[0]][0] = hen[1]
      tree[hen[0]][2] = True
    hens.remove(hen)

ret = [0 for i in range(n)]

def calc(p, x):
  global ret
  for child in tree[p][1]:
    calc(child, x)
  ret[p] += x

for i in range(q):
  calc(p[i], x[i])
print(*ret)

Submission status: Time Limit Exceeded

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

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

F = [0 for i in range(N)]
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

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

def dfs(x):
    if F[x] == 1:
        return
    F[x] = 1
    for j in range(len(T[x])):
        if F[T[x][j]] == 1:
            continue
        ans[T[x][j]] += ans[x]
        dfs(T[x][j])

dfs(0)

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

Submission status: Time Limit Exceeded

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


def main():
    n, q = map(int, input().split())
    e = [list(map(int, input().split())) for _ in range(n-1)]
    p = [list(map(int, input().split())) for _ in range(q)]

    e2 = [[] for _ in range(n)]
    for ee in e:
        a, b = ee
        e2[a-1].append(b-1)
        e2[b-1].append(a-1)

    counters = [0 for _ in range(n)]
    for pp in p:
        counters[pp[0]-1] += pp[1]

    used = [0] * n

    def dfs(x, p_sum):
        counters[x] += p_sum
        used[x] = 1
        for y in e2[x]:
            if used[y] == 1:
                continue
            dfs(y, counters[x])

    dfs(0, 0)
    print(*counters)


main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7)
 
n,q = map(int, input().split())
 
ki = [[] for i in range(n+1)]
for i in range(n-1):
    x,y = map(int, input().split())
    ki[x].append(y)
    ki[y].append(x)
    
p = [0] * (n+1)
for i in range(q):
    x,y = map(int, input().split())
    p[x] += y
 
def dfs(x, pre):
    global p
    global ki
 
    p[x] += p[pre]
 
    for i in ki[x]:
        if (i != pre):
            dfs(i, x)
 
dfs(1,0)
 
print(*(p[1:]))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(20000)

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

def dfs(v):
    for u in to[v]:
        ans[u] += ans[v]
        dfs(u)

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

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

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def bfs():
    for i in range(n):
        q = deque(tree[i])
        while q:
            v = q.popleft()
            for node in tree[v]:
                q.append(node)
                tree[i].append(node)


n, q = map(int, input().split())
tree = [[] for i in range(n)]
operate = [0] * n
ans = [0] * n
for _ in range(0, n - 1):
    a, b = map(int, input().split())
    tree[a - 1].append(b - 1)

bfs()

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

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
#%%
def dfs(gr,li):
    st = []
    seen = set()
    st.append([0,-1])
    while(st):
        x,fr = st.pop()
        if(x in seen):continue
        seen.add(x)
        if(fr != -1):
            li[x]+=li[fr]
            if(len(gr[x])==1):
                continue
        for i in gr[x]:
            if(i==fr):continue
            st[0:0] = [[i,x]]

#%%
def main():
    N,Q = [int(x) for x in input().split()]
    li = [0]*N
    gp = [[] for _ in range(N)]
    for _ in range(N-1):
        a,b = input().split()
        a = int(a)
        b = int(b)
        gp[a-1].append(b-1)
        gp[b-1].append(a-1)

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

    dfs(gp,li)
    print(*li)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

n,q=map(int,input().split())
tree = [set() for _ in range(n)]
for i in range(n-1):
    a,b=map(int,input().split())
    tree[a-1].add(b)
ans=[0]*n
def add_l(x):
    if not tree[x-1]:
        return
    for i in list(tree[x-1]):
        add_l(i)
        tree[x-1] |= tree[i-1]

add_l(1)
#print(tree)

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

        for j in list(tree[p-1]):
            ans[j-1]+=x
print(*ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(30000)

def find_child(a, f, c=[]):
    for x in a[f]:
        c.append(x)
        find_child(a, x, c)
    return c

n, q = map(int, input().split())
a = [[] for _ in range(n+1)]
cached = [None] * (n+1)
vals = [0] * (n)
for _ in range(n-1):
    e, f = map(int, input().split())
    a[e].append(f)
for _ in range(q):
    e, f = map(int, input().split())
    if not cached[e]: cached[e] = find_child(a, e, [])
    vals[e-1] += f
    for t in cached[e]: vals[t-1] += f
print(' '.join(map(str, vals)))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
#%%
def dfs(gr,li):
    st = []
    seen = set()
    st.append([0,-1])
    while(st):
        x,fr = st.pop()
        if(x in seen):continue
        if(fr != -1):
            li[x]+=li[fr]
        for i in gr[x]:
            if(i==fr):continue
            st[0:0] = [[i,x]]
        seen.add(x)

#%%
def main():
    N,Q = [int(x) for x in input().split()]
    li = [0]*N
    gp = [[] for _ in range(N)]
    for _ in range(N-1):
        a,b = input().split()
        a = int(a)
        b = int(b)
        gp[a-1].append(b-1)
        gp[b-1].append(a-1)

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

    dfs(gp,li)
    print(*li)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

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

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

def dfs(x, pre):
    global p
    global ki

    p[x] += p[pre]

    for i in ki[x]:
        if (i != pre):
            dfs(i, x)

dfs(1,0)

print(*(p[1:]))

Submission status: Time Limit Exceeded

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

#%%
def dfs(gr,li,pt,n,fr):
    li[n] += pt
    if(len(gr[n])==1 and gr[n][0]==fr):
        return True
    else:
        for i in gr[n]:
            if(i==fr):continue
            dfs(gr,li,li[n],i,n)
        return True
#%%
def main():
    N,Q = input().split()
    N = int(N)
    Q = int(Q)
    li = [0]*N
    gp = [[] for _ in range(N)]
    for _ in range(N-1):
        a,b = input().split()
        a = int(a)
        b = int(b)
        gp[a-1].append(b-1)
        gp[b-1].append(a-1)

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

    dfs(gp,li,0,0,-1)
    print(*li)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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


def solve(n, q, edges, p):
    counter = defaultdict(int)

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

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

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

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

    solve(n, q, edges, p)

Submission status: Time Limit Exceeded

Solution code:
n, q = map(int,input().split())
top_list = [list(map(int,input().split())) for i in range(n - 1)]
ope_list = [list(map(int,input().split())) for i in range(q)]

ans = [0] * n


for i in ope_list:
    ans[i[0] - 1] += i[1]

for j in range(n):
    for k in top_list:
        if j + 1 == k[1]:
            ans[j] += ans[k[0] - 1]


print(*ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
n,q=map(int,input().split())
tree = [set() for _ in range(n)]
for i in range(n-1):
    a,b=map(int,input().split())
    tree[a-1].add(b)
ans=[0]*n
def add_l(x):
    if not tree[x-1]:
        return
    for i in list(tree[x-1]):
        add_l(i)
        tree[x-1] |= tree[i-1]

add_l(1)
#print(tree)

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

        for j in list(tree[p-1]):
            ans[j-1]+=x
print(*ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)

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

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


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

counters = [0]*N

def dfs(node, accum):
    inc = queries[node]
    accum += inc
    counters[node] = accum
    for child in children[node]:
        assert(child != node)
        dfs(child, accum)

dfs(0, 0)
print(" ".join(map(str, counters)))

Submission status: Time Limit Exceeded

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

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

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

def dfs(v):
  for v_ in g[v]:
    ans[v_] += ans[v]
    dfs(v_)

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

Submission status: Time Limit Exceeded

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


def solve(n, q, edges, p):
    counter = defaultdict(int)


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

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

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

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

    solve(n, q, edges, p)

Submission status: Time Limit Exceeded

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

def eulartour(G):
    N = len(G)
    depth = [-1]*N
    depth[0] = 0
    eular = []
    L = [0]*N
    R = [0]*N
    i = 0
 
    def dfs(p):
        nonlocal depth, eular, i
        #eular.append(p)
        L[p] = i
        i += 1
        for q in G[p]:
            if depth[q] != -1:
                continue
            depth[q] = depth[p] + 1
            dfs(q)
        #eular.append(p)
        R[p] = i
        i += 1
    
    dfs(0)
    return L, R

class LazySegmentTree:
    
    def __init__(self, N, init_node=None, mode="max"):
        if mode == "sum":
            self.aggfunc = lambda x, y: x+y
            self.lazyaddfunc = lambda x, l, r: x*(r-l)
            self.lazyfunc = lambda x: x//2
        
        elif mode == "max":
            self.aggfunc = lambda x, y: x if x > y else y
            self.lazyaddfunc = lambda x, l, r: x
            self.lazyfunc = lambda x: x
        
        self.size = 2**int.bit_length(N)
        self.node = [0]*(2*self.size-1)
        if not init_node is None:
            for i in range(N):
                self.node[i+self.size-1] = init_node[i]
            for i in range(self.size-2, -1, -1):
                self.node[i] = self.aggfunc(self.node[2*i+1], self.node[2*i+2])
        self.lazy = [0]*(2*self.size-1)

    def eval(self, k, l, r):
        if self.lazy[k]:
            self.node[k] += self.lazy[k]
            if r-l-1:
                self.lazy[2*k+1] += self.lazyfunc(self.lazy[k])
                self.lazy[2*k+2] += self.lazyfunc(self.lazy[k])
            self.lazy[k] = 0

    def add(self, a, b, val):
        Q = [[0, 0, self.size]]
        Q2 = []

        def inner(k, l, r):
            nonlocal Q, Q2
            self.eval(k, l, r)
            if (b <= l) or (r <= a):
                return
            if (a<=l) and (r<=b):
                self.lazy[k] += self.lazyaddfunc(val, l, r)
                self.eval(k, l, r)
            else:
                Q.append([2*k+1, l, (l+r)//2])
                Q.append([2*k+2, (l+r)//2, r])
                Q2.append(k)

        while Q:
            inner(*Q.pop())
        
        while Q2:
            k = Q2.pop()
            self.node[k] = self.aggfunc(self.node[2*k+1], self.node[2*k+2])


    def getagg(self, a, b):
        ix = 0
        Q = [[0, 0, self.size, 0]]
        Q2 = []
        S = [0]

        def inner(k, l, r, i):
            nonlocal ix, Q, Q2, S
            if (b<=l) or (r <= a):
                return 0
            self.eval(k, l, r)
            if (a<=l) and (r<=b):
                S[i] = self.node[k]

            else:
                Q.append([2*k+1, l, (l+r)//2, ix+1])
                Q.append([2*k+2, (l+r)//2, r, ix+2])
                Q2.append([ix, ix+1, ix+2])
                S.extend([0, 0])
                ix += 2
        while Q:
            inner(*Q.pop())
        while Q2:
            x, y, z = Q2.pop()
            S[x] = self.aggfunc(S[y], S[z])
        return S[0]


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)

L, R = eulartour(G)

RSQ = LazySegmentTree(2*N)

for _ in range(Q):
    x, d = inpl()
    x -= 1
    RSQ.add(L[x], R[x]+1, d)
print(*[RSQ.getagg(L[i], L[i]+1) for i in range(N)])

Submission status: Time Limit Exceeded

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

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

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

def dfs(u, v):
  for v_ in g[v]:
    ans[v_] += ans[v]
    dfs(v, v_)

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

class tree:
    def __init__(self):
        self.baby_list=deque()
        self.counter=0
    
    def add_value(self):
        for i in self.baby_list:
            hoge[i].counter+=self.counter
            hoge[i].add_value()
            
N,Q=list(map(int, input().split() ))

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

for i in range(Q):
    root, value = list(map(int, input().split() ))
    hoge[root].counter+=value

hoge[1].add_value()
output = []
for t in hoge:
    output.append(hoge[t].counter)

    
output = list(map(str, output))
print(" ".join(output))

Submission status: Time Limit Exceeded

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

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

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

def dfs(u, v):
  for v_ in g[v]:
    if v_ == u:
      continue
    else:
      ans[v_] += ans[v]
      dfs(v, v_)

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

Submission status: Time Limit Exceeded

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

#%%
def dfs(gr,li,pt,n,fr):
    li[n] += pt
    if(len(gr[n])==1 and gr[n][0]==fr):
        return True
    else:
        for i in gr[n]:
            if(i==fr):continue
            dfs(gr,li,li[n],i,n)
        return True
#%%
def main():
    N,Q = [int(x) for x in input().split()]
    li = [0]*N
    gp = [[] for _ in range(N)]
    for _ in range(N-1):
        a,b = [int(x) for x in input().split()]
        gp[a-1].append(b-1)
        gp[b-1].append(a-1)

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

    dfs(gp,li,0,0,-1)
    print(*li)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

def eulartour(G):
    N = len(G)
    depth = [-1]*N
    depth[0] = 0
    eular = []
    L = [0]*N
    R = [0]*N
    i = 0
 
    def dfs(p):
        nonlocal depth, eular, i
        #eular.append(p)
        L[p] = i
        i += 1
        for q in G[p]:
            if depth[q] != -1:
                continue
            depth[q] = depth[p] + 1
            dfs(q)
        #eular.append(p)
        R[p] = i
        i += 1
    
    dfs(0)
    return L, R

class LazySegmentTree:
    
    def __init__(self, N, init_node=None, mode="max"):
        if mode == "sum":
            self.aggfunc = lambda x, y: x+y
            self.lazyaddfunc = lambda x, l, r: x*(r-l)
            self.lazyfunc = lambda x: x//2
        
        elif mode == "max":
            self.aggfunc = lambda x, y: x if x > y else y
            self.lazyaddfunc = lambda x, l, r: x
            self.lazyfunc = lambda x: x
        
        self.size = 2**int.bit_length(N)
        self.node = [0]*(2*self.size-1)
        if not init_node is None:
            for i in range(N):
                self.node[i+self.size-1] = init_node[i]
            for i in range(self.size-2, -1, -1):
                self.node[i] = self.aggfunc(self.node[2*i+1], self.node[2*i+2])
        self.lazy = [0]*(2*self.size-1)

    def eval(self, k, l, r):
        if self.lazy[k]:
            self.node[k] += self.lazy[k]
            if r-l-1:
                self.lazy[2*k+1] += self.lazyfunc(self.lazy[k])
                self.lazy[2*k+2] += self.lazyfunc(self.lazy[k])
            self.lazy[k] = 0

    def add(self, a, b, val):
        Q = [[0, 0, self.size]]
        Q2 = []

        def inner(k, l, r):
            nonlocal Q, Q2
            self.eval(k, l, r)
            if (b <= l) or (r <= a):
                return
            if (a<=l) and (r<=b):
                self.lazy[k] += self.lazyaddfunc(val, l, r)
                self.eval(k, l, r)
            else:
                Q.append([2*k+1, l, (l+r)//2])
                Q.append([2*k+2, (l+r)//2, r])
                Q2.append(k)

        while Q:
            inner(*Q.pop())
        
        while Q2:
            k = Q2.pop()
            self.node[k] = self.aggfunc(self.node[2*k+1], self.node[2*k+2])


    def getagg(self, a, b):
        ix = 0
        Q = [[0, 0, self.size, 0]]
        Q2 = []
        S = [0]

        def inner(k, l, r, i):
            nonlocal ix, Q, Q2, S
            if (b<=l) or (r <= a):
                return 0
            self.eval(k, l, r)
            if (a<=l) and (r<=b):
                S[i] = self.node[k]

            else:
                Q.append([2*k+1, l, (l+r)//2, ix+1])
                Q.append([2*k+2, (l+r)//2, r, ix+2])
                Q2.append([ix, ix+1, ix+2])
                S.extend([0, 0])
                ix += 2
        while Q:
            inner(*Q.pop())
        while Q2:
            x, y, z = Q2.pop()
            S[x] = self.aggfunc(S[y], S[z])
        return S[0]


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)

L, R = eulartour(G)

RSQ = LazySegmentTree(2*N)

for _ in range(Q):
    x, d = inpl()
    x -= 1
    RSQ.add(L[x], R[x]+1, d)
print(*[RSQ.getagg(L[i], L[i]+1) for i in range(N)])

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(100000)

#%%
def dfs(gr,li,pt,n,fr):
    li[n] += pt
    if(len(gr[n])==1 and gr[n][0]==fr):
        return True
    else:
        for i in gr[n]:
            if(i==fr):continue
            dfs(gr,li,li[n],i,n)
        return True
#%%
N,Q = [int(x) for x in input().split()]
li = [0]*N
gp = [[] for _ in range(N)]
for _ in range(N-1):
    a,b = [int(x) for x in input().split()]
    gp[a-1].append(b-1)
    gp[b-1].append(a-1)

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

dfs(gp,li,0,0,-1)
print(*li)

Submission status: Time Limit Exceeded

Solution code:
from sys import setrecursionlimit
setrecursionlimit(10**7)
N, Q = [int(x) for x in input().split()]
ab_list = [[int(x) for x in input().split()] for _ in range(N-1)]
px_list = [[int(x) for x in input().split()] for _ in range(Q)]
to = [[] for _ in range(N+1)]
for a, b in ab_list:
    a -= 1
    b -= 1
    to[b].append(a)
    to[a].append(b)
ans = [0] * N
for p, x in px_list:
    ans[p-1] += x

def dfs(v, p=-1):
    for u in to[v]:
        if (u == p): continue
        ans[u] += ans[v]
        dfs(u, v)        
dfs(0)
print(' '.join([str(i) for i in ans]))

Submission status: Time Limit Exceeded

Solution code:
from pprint import pprint
from collections import deque


def solve(n, q, edges, p):
    counter = [0] * n


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

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

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

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

    solve(n, q, edges, p)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
#%%
def dfs(gr,li):
    st = []
    seen = set()
    st.append([0,-1])
    while(st):
        x,fr = st.pop()
        if(x in seen):continue
        if(fr != -1):
            li[x]+=li[fr]
        for i in gr[x]:
            if(i==fr):continue
            st.insert(0,[i,x])
        seen.add(x)

#%%
def main():
    N,Q = [int(x) for x in input().split()]
    li = [0]*N
    gp = [[] for _ in range(N)]
    for _ in range(N-1):
        a,b = [int(x) for x in input().split()]
        gp[a-1].append(b-1)
        gp[b-1].append(a-1)

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

    dfs(gp,li)
    print(*li)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10 ** 9)
from bisect import bisect, bisect_left


class Node:
    def __init__(self, idx):
        self.idx = idx
        self.v = 0
        self.parent = None
        # self.children = []

    def make_tree(self, addval=0):
        self.v += addval
        keyidx = bisect_left(brs_keys, self.idx)
        while keyidx < len(brs_keys) and brs_keys[keyidx] == self.idx:
            ni = brs[keyidx][1]
            node = nodes[ni]
            # if not node.children:
            #     self.children.append(node)
            node.make_tree(self.v)
            keyidx += 1
        # for c in self.children:
        #     c.make_tree(self.v)

    def __str__(self):
        return str(self.idx)


N, Q = [int(_) for _ in input().split()]
nodes = [Node(i) for i in range(0, N)]

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

brs.sort()
brs_keys = [b[0] for b in brs]

# for n in nodes:
#     print(n.idx, [str(c) for c in n.children])

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

nodes[0].make_tree()

print(*[n.v for n in nodes])

Submission status: Time Limit Exceeded

Solution code:
def d_ki():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**6)
    N, Q = [int(i) for i in input().split()]

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

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

    # 1次元配列だったら単純に累積和を取ればいいのだが、木なので
    # DFSをしなければならない
    def dfs(current, parent=-1):
        for child in tree[current]:
            if child == parent:
                continue
            ans[child] += ans[current]
            dfs(child, current)
    dfs(0)
    return ' '.join(map(str, ans))

print(d_ki())

Submission status: Time Limit Exceeded

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

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

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

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

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

print(*op[1:])

Submission status: Time Limit Exceeded

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

#%%
def dfs(gr,li):
    st = []
    seen = set()
    st.append([0,-1])
    while(st):
        x,fr = st.pop()
        if(x in seen):continue
        if(fr != -1):
            li[x]+=li[fr]
        ns = [[i,x] for i in gr[x]]
        st[0:0] = ns
        seen.add(x)

#%%
def main():
    N,Q = [int(x) for x in input().split()]
    li = [0]*N
    gp = [[] for _ in range(N)]
    for _ in range(N-1):
        a,b = [int(x) for x in input().split()]
        gp[a-1].append(b-1)
        gp[b-1].append(a-1)

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

    dfs(gp,li)
    print(*li)

if __name__ == '__main__':
    main()