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:
def main():
    n, q = map(int, input().split())
    ab = [list(map(int, input().split())) for _ in [0]*(n-1)]
    px = [list(map(int, input().split())) for _ in [0]*q]
    g = [[] for _ in [0]*n]
    [g[a-1].append(b-1) for a, b in ab]
    [g[b-1].append(a-1) for a, b in ab]
    root = 0  # 根
    d = [-1]*n  # 根からの距離
    d[root] = 0
    q = [root]
    cnt = 0
    while q:  # BFS
        cnt += 1
        qq = []
        while q:
            i = q.pop()
            for j in g[i]:
                if d[j] == -1:
                    d[j] = cnt
                    qq.append(j)
        q = qq
    d2 = list(sorted(enumerate(d), key=lambda x: x[1]))

    ans = [0]*n
    for p, x in px:
        ans[p-1] += x
    for i, j in d2:
        for k in g[i]:
            if d[k] == j+1:
                ans[k] += ans[i]
    print(*ans)


main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

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

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

root_id = 1
open_list = [root_id]
closed_list = []
while True:
    if len(open_list) == 0:
        break
    cur_id = open_list.pop()
    closed_list.append(cur_id)
    adj_id_list = list(set(edge[cur_id]) - set(closed_list))
    for adj_id in adj_id_list:
        cnt[adj_id]+=cnt[cur_id]
        open_list.append(adj_id)
print(*cnt[1:])

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

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

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

root_id = 1
open_list = [root_id]
closed_list = []
while True:
    if len(open_list) == 0:
        break
    cur_id = open_list.pop()
    closed_list.append(cur_id)
    adj_id_list = edge[cur_id]
    for adj_id in adj_id_list:
        if adj_id in closed_list:
            continue
        cnt[adj_id]+=cnt[cur_id]
        open_list.append(adj_id)
print(*cnt[1:])

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

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

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

root_id = 1
open_list = [root_id]
closed_list = []
while True:
    if len(open_list) == 0:
        break
    cur_id = open_list.pop()
    closed_list.append(cur_id)
    adj_id_list = edge[cur_id]
    for adj_id in adj_id_list:
        if adj_id in closed_list:
            continue
        cnt[adj_id]+=cnt[cur_id]
        open_list.append(adj_id)
print(*cnt.values())

Submission status: Time Limit Exceeded

Solution code:
'''
pythonの再帰は10^5timesですら厳しい
import sys
sys.setrecursionlimit(10000000)

def dfs(v,p,G,c):
    for u in G[v]:
        if u!=p:
            c[u]+=c[v]
            dfs(u,v,G,c) 
'''
from collections import deque

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

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

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

stack=deque([0])
p = [-1]*N
a
while(stack):
    v = stack.pop()
    for u in G[v]:
        if u!=p[v]:
            c[u]+=c[v]
            p[u]=v
            stack.appendleft(u)


ans = ' '.join([str(x) for x in c])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000000)

#再帰を使って各ノードのカウンタの値を決定
def dfs(v,p):
    for u in G[v]:
        if u!=p:
            c[u]+=c[v]
            dfs(u,v) 
N,Q = list(map(int,input().split()))

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

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

dfs(0,-1)

ans = ' '.join([str(x) for x in c])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000000)

#再帰を使って各ノードのカウンタの値を決定
def dfs(v,p,G,c):
    for u in G[v]:
        if u!=p:
            c[u]+=c[v]
            dfs(u,v,G,c) 

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

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

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

dfs(0,-1,G,c)

ans = ' '.join([str(x) for x in c])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)
INF=10**18
def input():
    return sys.stdin.readline().rstrip()

def main():
    N,Q=map(int,input().split())
    a=[0]*(N-1)
    b=[0]*(N-1)
    cns=[[] for _ in range(N)]
    for i in range(N-1):
        a[i],b[i]=map(lambda x: int(x)-1,input().split())
        cns[a[i]].append(b[i])
        cns[b[i]].append(a[i])
    l_x=[0]*N
    for i in range(Q):
        p,x=map(int,input().split())
        l_x[p-1]+=x
    c=[0]*N
    c[0]+=l_x[0]
    def saiki(pn,ppn,x):
        for cn in cns[pn]:
            if cn != ppn:
                z=x+l_x[cn]
                c[cn]+=z
                saiki(cn,pn,z)
        return
    saiki(0,0,c[0])
    print(*c)
    

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def solve():
    N, Q = map(int, input().split())
    ab = [[0, 0] for _ in range(N-1)]
    for i in range(N-1):
        ab[i] = list(map(int, input().split()))
    px = [[0, 0] for _ in range(Q)]
    for i in range(Q):
        px[i] = list(map(int, input().split()))

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

    val = [0 for _ in range(N+1)]
    for p, x in px:
        val[p] += x

    que = deque([1])
    parent = [0 for _ in range(N+1)]
    while que:
        i = que.popleft()
        for j in graph[i]:
            if j == parent[i]:
                continue
            parent[j] = i
            que.append(j)
            val[j] += val[i]

    print(*val[1:])


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
def main():
    N, Q = map(int, input().split())
    d = {}
    for _ in range(N-1):
        a, b = map(int, input().split())
        if a in d:
            d[a].append(b)
        else:
            d[a] = [b]
        if b in d:
            d[b].append(a)
        else:
            d[b] = [a]
    dc = {}
    for _ in range(Q):
        p, x = map(int, input().split())
        if p in dc:
            dc[p] += x
        else:
            dc[p] = x
    v = set()
    vr = set(range(1,N+1))
    l = [0] * N
    n = [(1,0)]
    c = []
    while v != vr:
        for i, j in n:
            v.add(i)
            if i in dc:
                j += dc[i]
            l[i-1] = j
            for k in d[i]:
                if k not in v:
                    c.append((k, j))
        n = c
        c = []
    return ' '.join(str(i) for i in l)

print(main())

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(2 *(10**5) + 1)
def main():
    N, Q = map(int, input().split())
    d = {}
    for _ in range(N-1):
        a, b = map(int, input().split())
        if a in d:
            d[a].append(b)
        else:
            d[a] = [b]
        if b in d:
            d[b].append(a)
        else:
            d[b] = [a]
    dc = {}
    for _ in range(Q):
        p, x = map(int, input().split())
        if p in dc:
            dc[p] += x
        else:
            dc[p] = x
    v = set()
    l = [0] * N
    def dfs(n, p):
        v.add(n)
        if n in dc:
            p += dc[n]
        for i in d[n]:
            if i not in v:
                dfs(i, p)
        l[n-1] = p
    dfs(1, 0)
    return ' '.join(str(i) for i in l)

print(main())

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(2 *(10**5) + 1)
def main():
    N, Q = map(int, input().split())
    d = {}
    for _ in range(N-1):
        a, b = map(int, input().split())
        if a in d:
            d[a].append(b)
        else:
            d[a] = [b]
        if b in d:
            d[b].append(a)
        else:
            d[b] = [a]
    dc = {}
    for _ in range(Q):
        p, x = map(int, input().split())
        if p in dc:
            dc[p] += x
        else:
            dc[p] = x
    v = set()
    l = [0] * N
    def dfs(n, p):
        v.add(n)
        if n in dc:
            p += dc[n]
        for i in d[n]:
            if i not in v:
                dfs(i, p)
        l[n-1] = p
    dfs(1, 0)
    a = ''
    for i in l:
        a += str(i) + ' '
    return a[:-1]

print(main())

Submission status: Time Limit Exceeded

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

def main():
    N, Q = [int(i) for i in input().split()]
    V = [set() for _ in range(N)]
    for _ in range(N - 1):
        a, b = [int(i) - 1 for i in input().split()]
        V[a].add(b)
        V[b].add(a)
    C = [0] * N
    for _ in range(Q):
        p, x = [int(i) for i in input().split()]
        C[p - 1] += x
    def add(n, x, f):
        C[n] = x = C[n] + x
        for c in V[n]:
            if c != f:
                add(c, x, n)
    add(0, 0, 0)
    print(' '.join(str(c) for c in C))

main()

Submission status: Time Limit Exceeded

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

def main():
    N, Q = [int(i) for i in input().split()]
    V = [set() for _ in range(N)]
    for _ in range(N - 1):
        a, b = [int(i) - 1 for i in input().split()]
        V[a].add(b)
        V[b].add(a)
    C = [0] * N
    for _ in range(Q):
        p, x = [int(i) for i in input().split()]
        C[p - 1] += x
    def add(n, x):
        C[n] = x = C[n] + x
        for c in V[n]:
            V[c].remove(n)
            add(c, x)
    add(0, 0)
    print(' '.join(str(c) for c in C))

main()

Submission status: Time Limit Exceeded

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

def main():
    N, Q = [int(i) for i in input().split()]
    E = [tuple(int(i) for i in input().split()) for _ in range(N - 1)]
    V = [set() for _ in range(N)]
    for a, b in E:
        V[a - 1].add(b - 1)
        V[b - 1].add(a - 1)
    O = [tuple(int(i) for i in input().split()) for _ in range(Q)]
    C = [0] * N
    for p, x in O:
        C[p - 1] += x
    def add(n, x):
        C[n] += x
        for c in V[n]:
            V[c].remove(n)
            add(c, C[n])
    add(0, 0)
    print(' '.join(str(c) for c in C))

main()

Submission status: Time Limit Exceeded

Solution code:
from sys import setrecursionlimit
setrecursionlimit(3*10**5)

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

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


def rec(v, p=0):
    for t in T[v]:
        if t == p:
            continue
        C[t] += C[v]
        rec(t, v)


rec(1)
print(*C[1:])

Submission status: Time Limit Exceeded

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

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

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

check = [0 for _ in range(n)]
def dfs(st) :
  check[st] = 1
  for ne in tree[st] :
    if check[ne] == 1 :
      continue
    ans[ne] += ans[st]
    dfs(ne)

dfs(0)

print(*ans)

Submission status: Time Limit Exceeded

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

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

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

check = [0 for _ in range(n)]
def dfs(st) :
  check[st] = 1
  for ne in range(n) :
    if tree[st][ne] == 0 :
      continue
    if check[ne] == 1 :
      continue
    ans[ne] += ans[st]
    dfs(ne)

dfs(0)

print(*ans)

Submission status: Time Limit Exceeded

Solution code:
N,Q = map(int,input().split())
AB = [[] for _ in range(N-1)]
for n in range(N-1):
    AB[n] = list(map(int,input().split()))
PX = [[] for _ in range(Q)]
for q in range(Q):
    PX[q] = list(map(int,input().split()))
graph = [[] for _ in range(N+1)]
for ab in AB:
    graph[ab[0]].append(ab[1])
    graph[ab[1]].append(ab[0])
val = [0] * (N+1)
for px in PX:
    val[px[0]] += px[1]
parent = [0] * (N+1)
from collections import deque
Q  = deque([1])
while Q:
    q = Q.popleft()
    for c in graph[q]:
        if c == parent[q]:
            continue
        parent[c] = q
        Q.append(c)
        val[c] += val[q]
print(*val[1:])

Submission status: Time Limit Exceeded

Solution code:
N,Q = map(int,input().split())
AB = [[] for _ in range(N-1)]
for n in range(N-1):
    AB[n] = list(map(int,input().split()))
PX = [[] for _ in range(Q)]
for q in range(Q):
    PX[q] = list(map(int,input().split()))
graph = [[] for _ in range(N+1)]
for ab in AB:
    graph[ab[0]].append(ab[1])
    graph[ab[1]].append(ab[0])
val = [0] * (N+1)
for px in PX:
    val[px[0]] += px[1]
parent = [0] * (N+1)
Q  = [1]
while Q:
    q = Q.pop()
    for c in graph[q]:
        if c == parent[q]:
            continue
        parent[c] = q
        Q.append(c)
        val[c] += val[q]
print(*val[1:])

Submission status: Time Limit Exceeded

Solution code:
N,Q = map(int,input().split())
AB = [[] for _ in range(N-1)]
for n in range(N-1):
    AB[n] = list(map(int,input().split()))
PX = [[] for _ in range(Q)]
for q in range(Q):
    PX[q] = list(map(int,input().split()))
graph = [[] for _ in range(N+1)]
for ab in AB:
    graph[ab[0]].append(ab[1])
    graph[ab[1]].append(ab[0])
val = [0] * (N+1)
for px in PX:
    val[px[0]] += px[1]
parent = [0] * (N+1)
from collections import deque
Q  = deque([1])
while Q:
    q = Q.pop()
    for c in graph[q]:
        if c == parent[q]:
            continue
        parent[c] = q
        Q.append(c)
        val[c] += val[q]
print(*val[1:])

Submission status: Time Limit Exceeded

Solution code:
import sys, os
import collections

MOD = 10 ** 9 + 7

class Node:
  def __init__(self, to,  score = 0):
    super().__init__()
    self.to = to
    self.score = score

class DFS:
  def __init__(self, vertex = 0, parent = -1):
    super().__init__()
    self.vertex = vertex
    self.parent = parent
    

def solve(input_stream):
  N,Q = read_ints(input_stream)
  graph = []
  for index in range(N):
    graph.append(Node([]))
  for index in range(N-1):
    a,b = read_ints(input_stream)
    a-=1
    b-=1
    graph[a].to.append(b)
    graph[b].to.append(a)
  for index in range(Q):
    p,x = read_ints(input_stream)
    p-=1
    graph[p].score += x
  
  dfs = [DFS()]
  while len(dfs) > 0:
    state = dfs.pop(0)
    current_node = graph[state.vertex]
    for to in current_node.to:
      if to == state.parent:
        continue
      child_node = graph[to]
      child_node.score += current_node.score
      dfs.append(DFS(to, state.vertex))
  ans = []
  for i in graph:
    ans.append(str(i.score))
  return [" ".join(ans)]

def read_ints(input_stream):
  return [i for i in map(int, input_stream.readline().strip().split())]

def read_int(input_stream):
  return int(input_stream.readline().strip())


if __name__ == "__main__":
    outputs = solve(sys.stdin)
    for line in outputs:
      print(line)

Submission status: Time Limit Exceeded

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


def dfs(v, par):
    for nv in tree[v]:
        if nv != par:
            adds[nv] += adds[v]
            dfs(nv, v)


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

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
import sys

sys.setrecursionlimit(300000)

N, Q = map(int, input().split())
tree = defaultdict(list)
counter = [0] * N
for i in range(N-1):
    a, b = map(int, input().split())
    tree[a-1].append(b-1)
    tree[b-1].append(a-1)

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

visited = [False] * N


def dfs(parent):
    visited[parent] = True
    for child in tree[parent]:
        if not visited[child]:
            counter[child] += counter[parent]
            dfs(child)


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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
s=sys.stdin.readlines()
n,q=map(int,s[0].split())
G=[[]*n for i in range(n)]
P=[0]*n
V=[0]*n
R=[0]*n
for e in s[1:n]:
    a,b=map(int,e.split())
    G[a-1].append(b-1)
    G[b-1].append(a-1)
for e in s[n:]:
    c,d=map(int,e.split())
    P[c-1]+=d

def dsf(i,p):
    V[i]=1
    R[i]+=p+P[i]
    p=0
    if G[i]!=[]:
        for j in G[i]:
            if V[j]!=1:
                dsf(j,R[i])
dsf(0,0)
print(' '.join(map(str,R)))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
n,q=map(int,input().split())
G=[[]*n for i in range(n)]
P=[0]*n
V=[0]*n
for i in range(n-1):
	a,b=map(int,input().split())
	G[a-1].append(b-1)
	G[b-1].append(a-1)
for i in range(q):
	c,d=map(int,input().split())
	P[c-1]+=d
def dsf(i,p):
	V[i]=1
	P[i]+=p
	p=0
	for j in G[i]:
		if V[j]!=1:
			dsf(j,P[i])
dsf(0,0)
print(' '.join(map(str,P)))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
n,q=map(int,input().split())
G=[[]*n for i in range(n)]
P=[0]*n
V=[0]*n
R=[0]*n
for i in range(n-1):
	a,b=map(int,input().split())
	G[a-1].append(b-1)
	G[b-1].append(a-1)
for i in range(q):
	c,d=map(int,input().split())
	P[c-1]+=d

def dsf(i,p):
    V[i]=1
    R[i]+=p+P[i]
    p=0
    if G[i]!=[]:
        for j in G[i]:
            if V[j]!=1:
                dsf(j,R[i])
dsf(0,0)
print(' '.join(map(str,R)))

Submission status: Time Limit Exceeded

Solution code:
N,Q=[int(s) for s in input().split()]
edge=[set() for _ in range(N)]
value=[0 for _ in range(N)]
for i in range(N-1):
  x,y=[int(s) for s in input().split()]
  edge[x-1].add(y-1)
  edge[y-1].add(x-1)
for i in range(Q):
  x,y=[int(s) for s in input().split()]
  value[x-1]+=y
stack=[0]
while stack:
  vrt=stack.pop(0)
  for to in edge[vrt]:
    stack.append(to)
    edge[to].discard(vrt)
    value[to]+=value[vrt]
print(*value)

Submission status: Time Limit Exceeded

Solution code:
N,Q=[int(s) for s in input().split()]
edge=[set() for _ in range(N)]
value=[0 for _ in range(N)]
for i in range(N-1):
  x,y=[int(s) for s in input().split()]
  edge[x-1].add(y-1)
  edge[y-1].add(x-1)
for i in range(Q):
  x,y=[int(s) for s in input().split()]
  value[x-1]+=y
stack=[0]
while stack:
  vrt=stack.pop(0)
  for to in edge[vrt]:
    stack.append(to)
    value[to]+=value[vrt]
print(*value)

Submission status: Time Limit Exceeded

Solution code:
import sys

N,Q = [int(i) for i in sys.stdin.readline().split()]
D=[10**10]*N
D[0]=0
A=[[0]*3 for i in range(N-1)]
Ans=[0]*N
P=[[0]*2 for i in range(Q)]

for i in range(N-1):
    A[i][0],A[i][1] = [int(i) for i in sys.stdin.readline().split()]
    if(A[i][0]==1):
        D[A[i][1]-1]=1
    else:
        D[A[i][1]-1]=D[A[i][0]-1]+1
    A[i][2]=D[A[i][1]-1]
while(max(D)>(10**10)):
    for i in range(N-2,-1,-1):
        if(D[i]>(10**10)):
            D[A[i][1]-1]=D[A[i][0]-1]+1
        A[i][2]=D[A[i][1]-1]

for i in range(Q):
    P[i][0],P[i][1] = [int(i) for i in sys.stdin.readline().split()]
    Ans[P[i][0]-1]+=P[i][1]
A=sorted(A,key=lambda x: x[2])

for i in range (N-1):
    Ans[A[i][1]-1]+=Ans[A[i][0]-1]
print(*Ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

N,Q = [int(i) for i in sys.stdin.readline().split()]
D=[10**10]*N
D[0]=0
A=[[0]*3 for i in range(N-1)]
Ans=[0]*N
P=[[0]*2 for i in range(Q)]

for i in range(N-1):
    A[i][0],A[i][1] = [int(i) for i in sys.stdin.readline().split()]
    if(A[i][0]==1):
        D[A[i][1]-1]=1
    else:
        D[A[i][1]-1]=D[A[i][0]-1]+1
    A[i][2]=D[A[i][1]-1]
while(max(D)>(10**10)):
    for i in range(N-1):
        if(D[i]>(10**10)):
            D[A[i][1]-1]=D[A[i][0]-1]+1
        A[i][2]=D[A[i][1]-1]

for i in range(Q):
    P[i][0],P[i][1] = [int(i) for i in sys.stdin.readline().split()]
    Ans[P[i][0]-1]+=P[i][1]
A=sorted(A,key=lambda x: x[2])

for i in range (N-1):
    Ans[A[i][1]-1]+=Ans[A[i][0]-1]
print(*Ans)

Submission status: Time Limit Exceeded

Solution code:
N,Q = map(int, input().split())
D=[10**10]*N
D[0]=0
A=[[0]*3 for i in range(N-1)]
Ans=[0]*N
P=[[0]*2 for i in range(Q)]

for i in range(N-1):
    A[i][0],A[i][1] = map(int, input().split())
    if(A[i][0]==1):
        D[A[i][1]-1]=1
    else:
        D[A[i][1]-1]=D[A[i][0]-1]+1
    A[i][2]=D[A[i][1]-1]
while(max(D)>(10**10)):
    for i in range(N-1):
        if(D[i]>(10**10)):
            D[A[i][1]-1]=D[A[i][0]-1]+1
        A[i][2]=D[A[i][1]-1]

for i in range(Q):
    P[i][0],P[i][1] = map(int, input().split())
    Ans[P[i][0]-1]+=P[i][1]
A=sorted(A,key=lambda x: x[2])

for i in range (N-1):
    Ans[A[i][1]-1]+=Ans[A[i][0]-1]
print(*Ans)

Submission status: Time Limit Exceeded

Solution code:
N,Q = map(int, input().split())
D=[10**10]*N
D[0]=0
A=[[0]*3 for i in range(N-1)]
Ans=[0]*N
P=[[0]*2 for i in range(Q)]

for i in range(N-1):
    A[i][0],A[i][1] = map(int, input().split())
    if(A[i][0]==1):
        D[A[i][1]-1]=1
    else:
        D[A[i][1]-1]=D[A[i][0]-1]+1
    A[i][2]=D[A[i][1]-1]
while(max(D)>(10**10)):
    for i in range(N-1):
        if(A[i][0]==1):
            D[A[i][1]-1]=1
        else:
            D[A[i][1]-1]=D[A[i][0]-1]+1
        A[i][2]=D[A[i][1]-1]

for i in range(Q):
    P[i][0],P[i][1] = map(int, input().split())
    Ans[P[i][0]-1]+=P[i][1]
A=sorted(A,key=lambda x: x[2])

for i in range (N-1):
    Ans[A[i][1]-1]+=Ans[A[i][0]-1]
print(*Ans)

Submission status: Time Limit Exceeded

Solution code:
N,Q=[int(s) for s in input().split()]
edge=[set() for _ in range(N)]
value=[0 for _ in range(N)]
for i in range(N-1):
  x,y=[int(s) for s in input().split()]
  edge[x-1].add(y-1)
  edge[y-1].add(x-1)
for i in range(Q):
  x,y=[int(s) for s in input().split()]
  value[x-1]+=y
stack=[0]
while stack:
  vrt=stack.pop(0)
  for to in edge[vrt].copy():
    stack.append(to)
    value[to]+=value[vrt]
    edge[vrt].discard(to)
    edge[to].discard(vrt)
print(*value)

Submission status: Time Limit Exceeded

Solution code:
N,Q=[int(s) for s in input().split()]
edge=[set() for _ in range(N)]
value=[0 for _ in range(N)]
for i in range(N-1):
  x,y=[int(s) for s in input().split()]
  edge[x-1].add(y-1)
  edge[y-1].add(x-1)
for i in range(Q):
  x,y=[int(s) for s in input().split()]
  value[x-1]+=y
stack=[0]
while stack:
  vrt=stack.pop(0)
  for to in edge[vrt].copy():
    stack.append(to)
    value[to]+=value[vrt]
    edge[vrt].discard(to)
    edge[to].discard(vrt)
print(*value)

Submission status: Time Limit Exceeded

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

n, q = map(int, input().split())
C = [[] for _ in range(n)]
for _ in range(n-1):
  a, b = map(int, input().split())
  C[a-1].append(b-1)
  C[b-1].append(a-1)
dist = [-1]*n
dist[0] = 1
A = [0]*n
F = [0]*n
for _ in range(q):
  p, x = map(int, input().split())
  F[p-1] += x
def dfs1(v):
  for nv in C[v]:
    if dist[nv] == -1:
      dist[nv] = dist[v] + 1
      dfs1(nv)
dfs1(0)      
def dfs2(v):
  A[v] += F[v]
  for nv in C[v]:
    if dist[nv] > dist[v]:
      A[nv] += A[v]
      dfs2(nv)
dfs2(0)
print(*A)

Submission status: Time Limit Exceeded

Solution code:
n ,q = list(map(int,input().split()))
tree = [[] for i in range(n)]
for i in range(n-1):
    ai,bi = list(map(int,input().split()))
    tree[ai-1].append(bi)
    tree[bi-1].append(ai)
#print(tree)
plus = [0]*n
for i in range(q):
    p,x = list(map(int,input().split()))
    plus[p-1] += x
#print(plus)

stack = [1]
check = []
while len(stack) > 0:
    current = stack.pop()
    check.append(current)
    for i in range(len(tree[current-1])):
        if tree[current-1][i] not in check:
            stack.append(tree[current-1][i])
            plus[tree[current-1][i]-1] += plus[current-1]
#        print(i,current,stack,check)

print(*plus)

Submission status: Time Limit Exceeded

Solution code:
import sys

n, q = [int(i) for i in sys.stdin.readline().split()]
graph = {i: [] for i in range(n)}
ct = [0 for i in range(n)]
for i in range(n - 1):
    a, b = [int(i) for i in sys.stdin.readline().split()]
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

for i in range(q):
    p, x = [int(i) for i in sys.stdin.readline().split()]
    p -= 1
    ct[p] += x
already = {0}
que = [(0, ct[0], -1)]
res = [0 for i in range(n)]
while len(que) > 0:
    cur, cost, _from = que.pop(0)
    res[cur] = cost
    for _next in graph[cur]:
        if _next == _from:
            continue
        next_cost = ct[_next]
        que.append((_next, cost + next_cost, cur))
        already.add(cur)
print(" ".join([str(r) for r in res]))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7)
n, q = [int(i) for i in sys.stdin.readline().split()]
graph = {i : [] for i in range(n)}
ct = [0 for i in range(n)]
inp = sys.stdin.readlines()
a_b = inp[:n-1]
p_x = inp[n-1:]
for i in a_b:
    a, b = [int(j) for j in i.split()]
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

for i in p_x:
    p, x = [int(j) for j in i.split()]
    p -= 1
    ct[p] += x
already = {0}
que = [(0, ct[0])]
res = [0 for i in range(n)]
while len(que) > 0:
    cur, cost = que.pop(0)
    res[cur] = cost
    for _next in graph[cur]:
        if _next in already:
            continue
        next_cost = ct[_next]
        que.append((_next, cost + next_cost))
        already.add(cur)
print(" ".join([str(r) for r in res]))

Submission status: Time Limit Exceeded

Solution code:
import sys
n, q = [int(i) for i in sys.stdin.readline().split()]
graph = {i : [] for i in range(n)}
ct = [0 for i in range(n)]
for i in range(n-1):
    a, b = [int(i) for i in sys.stdin.readline().split()]
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)

for i in range(q):
    p, x = [int(i) for i in sys.stdin.readline().split()]
    p -= 1
    ct[p] += x
already = {0}
que = [(0, ct[0])]
res = [0 for i in range(n)]
while len(que) > 0:
    cur, cost = que.pop(0)
    res[cur] = cost
    for _next in graph[cur]:
        if _next in already:
            continue
        next_cost = ct[_next]
        que.append((_next, cost + next_cost))
        already.add(cur)
print(" ".join([str(r) for r in res]))

Submission status: Time Limit Exceeded

Solution code:
N, Q = map(int, input().split())

l = [set() for i in range(N)]

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

par = [-1] * N
par[0] = 0

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

stack = [0]
while stack:
  prev = stack.pop()
  for to in l[prev]:
    if par[to] < 0:
      par[to] = prev
      children[prev].append(to)
      stack.append(to)

counter = [0] * N

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

r = [-1] * N
r[0] = counter[0]

stack = [0]
while stack:
  i = stack.pop()
  stack += children[i]
  s = 0
  cur = i
  while r[cur] < 0:
    s += counter[cur]
    cur = par[cur]
  r[i] = r[cur] + s

print(*r)

Submission status: Time Limit Exceeded

Solution code:
N, Q = map(int, input().split())

l = [set() for i in range(N)]

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

par = [-1] * N
par[0] = 0

stack = [0]
while stack:
  prev = stack.pop()
  for to in l[prev]:
    if par[to] < 0:
      par[to] = prev
      stack.append(to)

counter = [0] * N

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

r = [-1] * N
r[0] = counter[0]

for i in range(N):
  s = 0
  cur = i
  while r[cur] < 0:
    s += counter[cur]
    cur = par[cur]
  r[i] = r[cur] + s

print(*r)

Submission status: Time Limit Exceeded

Solution code:
#pypyはinput使えない

import sys
n,q=map(int,sys.stdin.readline().split())
tree=[list(map(int,sys.stdin.readline().split())) for i in range(n-1)]
#f1は使ったのかどうかを表すフラッグ
#f2はそれまでに出てきたものを表すフラッグ
f1=[0]*(n-1)
f2=[0]*n
f2[0]=1

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

while f1!=[1]*(n-1):
    for i,t in enumerate(tree):
        if f1[i]==0:
            if f2[t[0]-1]==1:
                c[t[1]-1]+=c[t[0]-1]
                f1[i]=1
                f2[t[1]-1]=1
            elif f2[t[1]-1]==1:
                c[t[0]-1]+=c[t[1]-1]
                f1[i]=1
                f2[t[0]-1]=1
            else:
                pass

print(" ".join([str(k) for k in c]))