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
from collections import defaultdict
def wi(): return list(map(int, sys.stdin.readline().split()))
def i(): return int(sys.stdin.readline())
def mi(n): return [wi() for _ in range(n)]#MatrixInt

def main():
    n, q = wi()
    ab = mi(n - 1)
    px = mi(q)
    numdict = {}
    for i in range(n + 1):
        numdict[i] = []

    parli = [0] * (n + 1)
    parli[1] = 1
    for i in range(n - 1):
        if parli[ab[i][0]] == 0:
            parli[ab[i][0]] = 1
        else:
            numdict[ab[i][0]].append(ab[i][1])
        if parli[ab[i][1]] == 0:
            parli[ab[i][1]] = 1
        else:
            numdict[ab[i][1]].append(ab[i][0])

    plsdict = defaultdict(int)
    for i in range(q):
        plsdict[px[i][0]] += px[i][1]



    queue = []
    queue.append(1)
    while queue != []:
        po = queue.pop()
        for kk in numdict[po]:
            queue.append(kk)
            plsdict[kk] += plsdict[po]

    for i in range(1, n + 1):
        print(plsdict[i],"" , end="")

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

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

Solution code:
import sys

sys.setrecursionlimit(10**9)

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
re = sys.stdin.readline
N, Q = map(int, re().split())
graph = [[] for _ in range(N)]
for i in range(N - 1):
    a, b = map(int, re().split())
    graph[a - 1].append(b - 1)
    graph[b - 1].append(a - 1)
items = [0] * N
for i in range(Q):
    q, x = map(int, input().split())
    items[q - 1] += x
sys.setrecursionlimit(10 ** 9)

ans = [0] * N
def dfs2(tar,pre, plus):
    tmp = plus + items[tar]
    ans[tar] = tmp
    for v in graph[tar]:
        if v == pre:
            continue
        dfs2(v, tar, tmp)


dfs2(0,-1, 0)

for a in ans:
    print(a, end=" ")

Submission status: Time Limit Exceeded

Solution code:
import sys
re = sys.stdin.readline
N, Q = map(int, re().split())
graph = [[] for _ in range(N)]
for i in range(N - 1):
    a, b = map(int, re().split())
    graph[a - 1].append(b - 1)
    graph[b - 1].append(a - 1)
items = [0] * N
for i in range(Q):
    q, x = map(int, input().split())
    items[q - 1] += x
import sys

sys.setrecursionlimit(10 ** 9)

ans = [0] * N

def dfs2(tar,pre, plus):
    ans[tar] += plus + items[tar]
    for v in graph[tar]:
        if v == pre:
            continue
        dfs2(v, tar, ans[tar])


dfs2(0,-1, 0)

for a in ans:
    print(a, end=" ")

Submission status: Time Limit Exceeded

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

Solution code:
import sys
re = sys.stdin.readline
N, Q = map(int, re().split())
graph = [[] for _ in range(N)]
for i in range(N - 1):
    a, b = map(int, re().split())
    graph[a - 1].append(b - 1)
    graph[b - 1].append(a - 1)
items = [0] * N
for i in range(Q):
    q, x = map(int, input().split())
    items[q - 1] += x

p = [-1] * N
import sys

sys.setrecursionlimit(10 ** 9)

ans = [0] * N

def dfs2(tar,pre, plus):
    ans[tar] += plus + items[tar]
    for v in graph[tar]:
        if v == pre:
            continue
        dfs2(v, tar, ans[tar])


dfs2(0,-1, 0)

for a in ans:
    print(a, end=" ")

Submission status: Time Limit Exceeded

Solution code:
import sys

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

Solution code:
N, Q = map(int, input().split())
graph = [[] for _ in range(N)]
for i in range(N - 1):
    a, b = map(int, input().split())
    graph[a - 1].append(b - 1)
    graph[b - 1].append(a - 1)
items = [0] * N
for i in range(Q):
    q, x = map(int, input().split())
    items[q - 1] += x

p = [-1] * N
import sys

sys.setrecursionlimit(10 ** 9)

ans = [0] * N


def dfs2(tar,pre, plus):
    ans[tar] += plus + items[tar]

    for v in graph[tar]:
        if v == pre:
            continue
        dfs2(v, tar, ans[tar])


dfs2(0,-1, 0)

for a in ans:
    print(a, end=" ")

Submission status: Time Limit Exceeded

Solution code:
N, Q = map(int, input().split())
graph = [[] for _ in range(N)]
for i in range(N - 1):
    a, b = map(int, input().split())
    graph[a - 1].append(b - 1)
    graph[b - 1].append(a - 1)
items = [0] * N
for i in range(Q):
    q, x = map(int, input().split())
    items[q - 1] += x

p = [-1] * N
import sys

sys.setrecursionlimit(10 ** 9)


def dfs(start, tar):
    p[tar] = start
    for v in graph[tar]:
        if v == start:
            continue
        dfs(tar, v)


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


def dfs2(tar, plus):
    ans[tar] += plus + items[tar]

    for v in graph[tar]:
        if v == p[tar]:
            continue
        dfs2(v, ans[tar])


dfs2(0, 0)

for a in ans:
    print(a, end=" ")

Submission status: Time Limit Exceeded

Solution code:
import sys
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: Time Limit Exceeded

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

#=====================================
class Tree():
  def __init__(self):
    self.root = None
    self.children = set()
    self.counter = 0

  def add_child(self, child):
    self.children.add(child)
  
  def reconstruct(self, root=None):
    if root in self.children:
      self.root = root
      self.children.remove(root)
    for child in self.children:
      child.reconstruct(self)
  
  def add_count(self, x):
    self.counter += x

  def get_count(self):
    res = self.counter
    if self.root:
      res += self.root.get_count()
    return res
      
#=====================================

def solve():
  n,q = [int(i) for i in input().split()]
  trees = [Tree() for i in range(n)]

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

  trees[0].reconstruct()

  for _ in range(q):
    p,x = [int(i) for i in input().split()]
    trees[p-1].add_count(x)

  print(*[trees[i].get_count() for i in range(n)])

if __name__ == '__main__':
  solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque, defaultdict
def wi(): return list(map(int, sys.stdin.readline().split()))
def i(): return int(sys.stdin.readline())
def mi(n): return [wi() for _ in range(n)]#MatrixInt

def main():
    n, q = wi()
    ab = mi(n - 1)
    px = mi(q)
    numdict = {}
    for i in range(n + 1):
        numdict[i] = []

    parli = [0] * (n + 1)
    parli[1] = 1
    for i in range(n - 1):
        if parli[ab[i][0]] == 0:
            parli[ab[i][0]] = 1
        else:
            numdict[ab[i][0]].append(ab[i][1])
        if parli[ab[i][1]] == 0:
            parli[ab[i][1]] = 1
        else:
            numdict[ab[i][1]].append(ab[i][0])

    plsdict = defaultdict(int)
    for i in range(q):
        plsdict[px[i][0]] += px[i][1]



    queue = deque()
    queue.append(1)
    while queue != deque():
        po = queue.popleft()
        for kk in numdict[po]:
            queue.append(kk)
            plsdict[kk] += plsdict[po]

    for i in range(1, n + 1):
        print(plsdict[i],"" , end="")

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

#=====================================
class Tree():
  def __init__(self):
    self.root = None
    self.children = []
    self.counter = 0

  def add_child(self, child):
    self.children += [child]
  
  def reconstruct(self, root=None):
    if root in self.children:
      self.root = root
      self.children.remove(root)
    for child in self.children:
      child.reconstruct(self)
  
  def add_count(self, x):
    self.counter += x

  def get_count(self):
    res = self.counter
    if self.root:
      res += self.root.get_count()
    return res
      
#=====================================

def solve():
  n,q = [int(i) for i in input().split()]
  trees = [Tree() for i in range(n)]

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

  trees[0].reconstruct()

  for _ in range(q):
    p,x = [int(i) for i in input().split()]
    trees[p-1].add_count(x)

  print(*[trees[i].get_count() for i in range(n)])

if __name__ == '__main__':
  solve()

Submission status: Time Limit Exceeded

Solution code:
N, Q = map(int,input().split())
edge = [[] for i in range(N)]
val = [0 for i in range(N)]
decide = [0 for i in range(N)]
for i in range(N-1):
    a, b = map(int,input().split())
    edge[a-1].append(b-1)
    edge[b-1].append(a-1)
for i in range(Q):
    n, v = map(int,input().split())
    val[n-1] += v
 
queue = [0]
while queue:
    op = queue.pop(0)
    while edge[op]:
        a = edge[op].pop(0)
        if decide[a] == 0:
            val[a] += val[op]
            queue.append(a)
    decide[op] = 1
print(*val)

Submission status: Time Limit Exceeded

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

#=====================================
class Tree():
  def __init__(self):
    self.children = []
    self.counter = 0

  def add_child(self, child):
    self.children += [child]
  
  def reconstruct(self, root=None):
    if root in self.children:
      self.children.remove(root)
    for child in self.children:
      child.reconstruct(self)
  
  def add_count(self, x):
    self.counter += x
    for child in self.children:
      child.add_count(x)

#=====================================
def solve():
  n,q = [int(i) for i in input().split()]
  trees = [Tree() for i in range(n)]

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

  trees[0].reconstruct()

  for _ in range(q):
    p,x = [int(i) for i in input().split()]
    trees[p-1].add_count(x)

  print(*[trees[i].counter for i in range(n)])
  
#=====================================
if __name__ == '__main__':
  solve()

Submission status: Time Limit Exceeded

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

#=====================================
class Tree():
  def __init__(self):
    self.children = []
    self.counter = 0

  def add_child(self, child):
    self.children += [child]
  
  def reconstruct(self, root=None):
    if root in self.children:
      self.children.remove(root)
    for child in self.children:
      child.reconstruct(self)
  
  def add_count(self, x):
    self.counter += x
    for child in self.children:
      child.add_count(x)

#=====================================

n,q = [int(i) for i in input().split()]
trees = [Tree() for i in range(n)]

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

trees[0].reconstruct()

for _ in range(q):
  p,x = [int(i) for i in input().split()]
  trees[p-1].add_count(x)

print(*[trees[i].counter for i in range(n)])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
#ABC138 D

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n,q = LI()
g = [[] for _ in range(n)]
for _ in range(n-1):
    a,b = LI()
    g[a-1].append(b-1)
    g[b-1].append(a-1)

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

def dfs(start,par):
    for v in g[start]:
        if v != par:
            ans[v] += ans[start]
            dfs(v,start)
dfs(0,-1)
print(*ans)

Submission status: Time Limit Exceeded

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


def dfs(i, j=-1):
    global g
    for k in g[i]:
        if k == j:
            continue

        ans[k] += ans[i]
        dfs(k, i)


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())
    ans[p-1] += x

dfs(0)
print(*ans)

Submission status: Time Limit Exceeded

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

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

def dfs(v=0, pv=-1, res=0):
    res += cnt[v]
    ans_list[v] = res
    for nv in ad[v]:
        if nv == pv:
            continue
        dfs(nv, v, res)

dfs()

print(*ans_list)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin,setrecursionlimit
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: Time Limit Exceeded

Solution code:

import sys
from collections import deque, defaultdict
import copy
import bisect
#input=sys.stdin.readline
#sys.setrecursionlimit(10 ** 9)
import math
import heapq


N, Q = list(map(int, input().split()))
eda = [[] for i in range(N)]
ope = [0]*N
score = [0]*N
parent = [-1]*N


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

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


que = []
que.append(0)
score[0] = ope[0]
for ss in range(N - 1):
	loc = que.pop()
	for edge in eda[loc]:
		if parent[loc] != edge:
			score[edge] += score[loc] + ope[edge]
			que.append(edge)
			parent[edge] = loc

for i in range(N - 1):
	print(score[i], end = "")
	print(" ", end = "")
print(score[N - 1])

Submission status: Time Limit Exceeded

Solution code:


N, Q = list(map(int, input().split()))
eda = [[] for i in range(N)]
ope = [0]*N
score = [0]*N
parent = [-1]*N


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

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


que = []
que.append(0)
score[0] = ope[0]
for ss in range(N - 1):
	loc = que.pop()
	for edge in eda[loc]:
		if parent[loc] != edge:
			score[edge] += score[loc] + ope[edge]
			que.append(edge)
			parent[edge] = loc

for i in range(N - 1):
	print(score[i], end = "")
	print(" ", end = "")
print(score[N - 1])

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin,setrecursionlimit
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 = -1):
    global d
    for p in T[u]:
        if p == v:
            continue
        d[p] += d[u]
        dfs(p, u)

dfs(0)

for v in d:
    print(v)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000) 

N, Q = map(int, input().split())
T = [[] for i in range(2 * (10 ** 5))]
for i 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 i in range(Q):
    p, x = map(int, input().split())
    d[p - 1] += x

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

dfs(0)

for v in d:
    print(v)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000) 

N, Q = map(int, input().split())
T = [[] for i in range(2 * (10 ** 5))]
for i 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 i in range(Q):
    p, x = map(int, input().split())
    d[p - 1] += x

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

dfs(0)


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

Submission status: Time Limit Exceeded

Solution code:
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

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

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

dfs(0, -1)

print(*ans)

Submission status: Time Limit Exceeded

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

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

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

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

dfs(0, -1)

print(*ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)

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)
for i in range(n):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000000) 
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: Time Limit Exceeded

Solution code:

import sys
sys.setrecursionlimit(1000000) 

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

d = [0] * N

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

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

dfs(0)


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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000) 

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

Solution code:
import sys
sys.setrecursionlimit(100000000) 
 

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

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

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


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

Solution code:
import sys
sys.setrecursionlimit(1000000) 
 

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

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

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


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

Solution code:
n, q = map(int,input().split())
cnt = [0] * (n+1)
import sys
sys.setrecursionlimit(10**6)
import numpy as np
tree = [[] for _ in range(n+1)]
seen = [0] * (n+1)
child = [0] * (n+1)
for i in range(n-1):
    a, b = map(int,input().split())
    tree[a].append(b)
    tree[b].append(a)
for _ in range(q):
    p,x = map(int,input().split())
    cnt[p] += x

def dfs(i):
    global child
    global cnt
    child[i] = []
    if tree[i] == []:
        seen[i] = 1
        return
    for j in tree[i]:
        if seen[j] == 0:
            child[i].append(j)
            cnt[j] += cnt[i]
            seen[i] = 1
            dfs(j)
    return

dfs(1)
print(*cnt[1:])

Submission status: Time Limit Exceeded

Solution code:
n, q = map(int,input().split())
cnt = [0] * (n+1)
import sys
sys.setrecursionlimit(10**6)
import numpy as np
tree = [[] for _ in range(n+1)]
seen = [0] * (n+1)
child = [0] * (n+1)
for i in range(n-1):
    a, b = map(int,input().split())
    tree[a].append(b)
    tree[b].append(a)
def dfs(i):
    global child
    child[i] = []
    if tree[i] == []:
        seen[i] = 1
        return
    for j in tree[i]:
        if seen[j] == 0:
            child[i].append(j)
            seen[i] = 1
            dfs(j)
    return

dfs(1)
#print(child)
for _ in range(q):
    p,x = map(int,input().split())
    cnt[p] += x
def plus(c):
    global cnt
    if child[c] == []:
        return
    for target in child[c]:
        cnt[target] += cnt[c]
        plus(target)
    return
plus(1)
print(*cnt[1:])

Submission status: Time Limit Exceeded

Solution code:
class Node:
    def __init__(self, id):
        self.id = id
        self.value = 0
        self.children = []
    
    def spread(self):
        if len(self.children)==0:
            return
        
        for child in self.children:
            child.value += self.value
            child.spread()
        

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

edges = [tuple(map(int, input().split())) for _ in range(n-1)]
nodedict = dict()
root = Node(1)
nodedict[root.id] = root

marked = [root.id]
while len(edges) > 0:
    tmp = []
    rm = []
    for i, edge in enumerate(edges):
        if edge[0] in marked:
            new = Node(edge[1])
            nodedict[edge[1]] = new
            nodedict[edge[0]].children.append(new)
            rm.append(edge)
            tmp.append(edge[1])
        elif edge[1] in marked:
            new = Node(edge[0])
            nodedict[edge[0]] = new
            nodedict[edge[1]].children.append(new)
            rm.append(edge)
            tmp.append(edge[0])
    marked = tmp
    for r in rm:
      edges.remove(r)

for _ in range(q):
    p, x = map(int, input().split())
    nodedict[p].value += x

root.spread()

print(' '.join([str(nodedict[i].value) for i in range(1, n+1)]))

Submission status: Time Limit Exceeded

Solution code:
#import pysnooper
#import os,re,sys,operator,math,heapq,string
#from collections import Counter,deque
#from operator import itemgetter
#from itertools import accumulate,combinations,groupby
from sys import stdin,setrecursionlimit
#from copy import deepcopy

setrecursionlimit(10**6)

def rec(pp,xx=-1):
    for i in gragh[pp]:
        if i==xx:
            continue
        ans[i]+=ans[pp]
        rec(i,pp)

n,q=map(int,stdin.readline().rstrip().split())
ans=[0]*n
gragh=[[]*n for _ in range(n)]
for _ in range(n-1):
    a,b=map(int,stdin.readline().rstrip().split())
    a-=1
    b-=1

    gragh[a].append(b)
    gragh[b].append(a)
for _ in range(q):
    p,x=map(int,stdin.readline().rstrip().split())
    ans[p-1]+=x
rec(0)
print(*ans)

Submission status: Time Limit Exceeded

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

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

add_list = []
for i in range(q):
    p = list(map(int, input().split()))
    add_list.append(p)

#print(edge,add_list)


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

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


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


dp = [-1] * n

def dfs(index, parent,value):
    if (dp[index] != -1):
        return dp[index]
    value += add_value[index]
    dp[index] = value
    for i in dir_edge[index]:
        if (parent == i):
            continue
        dfs(i,index,value)
        

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

Submission status: Time Limit Exceeded

Solution code:
#import pysnooper
import os,re,sys,operator,math,heapq,string
from collections import Counter,deque
from operator import itemgetter
from itertools import accumulate,combinations,groupby
from sys import stdin,setrecursionlimit
from copy import deepcopy

setrecursionlimit(10**6)

def rec(pp,xx=-1):
    for i in gragh[pp]:
        if i==xx:
            continue
        ans[i]+=ans[pp]
        rec(i,pp)

n,q=map(int,stdin.readline().rstrip().split())
ans=[0]*n
gragh=[[]*n for _ in range(n)]
for i in range(n-1):
    a,b=map(int,stdin.readline().rstrip().split())
    a-=1
    b-=1
    gragh[a].append(b)
    gragh[b].append(a)
for i in range(q):
    p,x=map(int,stdin.readline().rstrip().split())
    ans[p-1]+=x
rec(0)
print(*ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(100000)

# お約束
INF = float("inf")
MOD = int(1e9 + 7)

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

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

edges = [[] for _ in range(N)]
for a, b in AB:
	a, b = a - 1, b - 1
	edges[a] += [b]
	edges[b] += [a]

visited = [False] * N
vals = [0] * N

def dfs(v, p, add_val):
	global visited, vals
	visited[v] = True
	vals[v] = add_val + sum_val[v]
	for n in edges[v]:
		if visited[n]: continue
		dfs(n, v, add_val + sum_val[v])

dfs(0, -1, 0)
for v in vals:
	print(v)