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: Runtime Error

Solution code:
n,q=map(int,input().split())
tree=[0]*n
connection=[]
for i in range(n):
    connection.append([])
def connect(a,b):#aはbより上にある
    connection[a-1].append(b)
    pass
def kasan(p,x):
    tree[p-1]+=x
    for i in range(len(connection[p-1])):
        kasan(connection[p-1][i],x)
for i in range(n-1):
    a,b=map(int,input().split())
    connect(a,b)
for i in range(q):
    p,x=map(int,input().split())
    kasan(p,x)
print(*tree)

Submission status: Runtime Error

Solution code:
n, q = map(int, input().split())
adj = [[] for i in range(n)]
for i in range(n-1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    adj[a].append(b)
    adj[b].append(a)
tour = []
invtour = [0] * n
size = [1] * n

t = 0
def dfs(u, p):
    global adj, invtour
    global t
    invtour[u] = t
    t += 1
    tour.append(u)
    for v in adj[u]:
        if v != p:
            dfs(v, u)
            size[u] += size[v]
dfs(0, -1)
diff = [0] * (n + 1)

for j in range(q):
    p, x = map(int, input().split())
    p -= 1
    diff[invtour[p]] += x
    diff[invtour[p]+size[p]] -= x
    
for i in range(1, n):
    diff[i] += diff[i - 1]
for i in range(n):
    print(diff[invtour[i]], end=" ")

Submission status: Runtime Error

Solution code:
N, Q = list(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) ]
lst = [[] for _ in range(N)]
ans = [0] * N

for i in range(N-1):
    a = min(AB[i][0],AB[i][1])
    b = max(AB[i][0],AB[i][1])
    lst[a-1].append(b)


        
def fun(p,x):
    ans[p-1] += x
    for tmp in lst[p-1]:
        fun(tmp,x)
        

for i in range(Q):
    p = PX[i][0]
    x = PX[i][1]
    fun(p,x)

for i in range(N):
    ans[i] = str(ans[i])

ans = " ".join(ans)
print(ans)

Submission status: Runtime Error

Solution code:
class Node:
    def __init__(self, index):
        self.count = 0
        self.next = []
        self.index = index


def f(node, count, index):
    node[index].count += count
    for i in node[index].next:
        f(node, count, i)


N, Q = map(int, input().split())
node = [Node(i) for i in range(N)]
for i in range(N - 1):
    fr, to = map(int, input().split())
    node[fr - 1].next.append(to - 1)

for i in range(Q):
    fr, c = map(int, input().split())
    f(node, c, fr - 1)

print(' '.join([str(n.count) for n in node]))

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
nodes = {}
for _ in range(N-1):
    a, b = input().split()
    if nodes.get(a) is None:
        nodes[a] = [b]
    else:
        nodes[a] += [b]

PX = [input().split() for _ in range(Q)]

ptree_map = {}


def gen_subtree_nodes(node):
    res = [int(node)]
    for n in nodes.get(node, []):
        subtree_nodes = gen_subtree_nodes(n)
        ptree_map[n] = subtree_nodes
        res += subtree_nodes

    return res


ptree_map['1'] = gen_subtree_nodes('1')

node_cnts = [0] * (N+1)
for p, x_str in PX:
    x = int(x_str)
    for n in ptree_map[p]:
        node_cnts[n] += x

print(*node_cnts[1:])

Submission status: Runtime Error

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

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

v_list = [0 for _ in range(n)]


def add_v(num, value):
    v_list[num-1] = v_list[num-1]+value
    if num in dic:
        for root in dic[num]:
            add_v(root, value)


for i in range(q):
    p,x=map(int,input().split())
    add_v(p, x)

print(*v_list)

Submission status: Runtime Error

Solution code:
def Plus(value, index, Child, Values):
    Values[index] += value
    if len(Child[index]) == 0:
        return
    for c in Child[index]:
        Plus(value, c, Child, Values)


def main():
    N, Q = map(int, input().split())
    Child = [[] for _ in range(N+1)]
    Values = [0 for _ in range(N+1)]

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

    for j in range(Q):
        p, x = map(int, input().split())
        Plus(x, p, Child, Values)

    print(*Values[1:])


if __name__ == "__main__":
    main()

Submission status: Runtime Error

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

tree = [[] for _ in range(n)]
ope = [0]*n
ret=[0]*n

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

def counter(target,num):
    global ret
    ret[target]+=num
    if not tree[target]:
        return
    for i in tree[target]:
        counter(i,num)

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

for i in range(n):
    counter(i,ope[i])

print(*ret)

Submission status: Runtime Error

Solution code:
n,q=map(int,input().split())
ab=[[0]*2 for i in range(n-1)]
px=[[0]*2 for i in range(q)]
for i in range(n-1):
    ab[i][0],ab[i][1]=map(int,input().split())
for i in range(q):
    px[i][0],px[i][1]=map(int,input().split())
# print(ab)
# print(px)
node=[[0] for i in range(n+1)]
for i in range(n-1):
    node[ab[i][0]].append(ab[i][1])
for i in range(q):
    node[px[i][0]][0]+=px[i][1]
# print(node)
ans=[0]*(n+1)

def flow(n):
    # print(n)
    # print(node)
    # print(ans)
    # print(len(node[n]))
    ans[n]+=node[n][0]
    for i in range(1,len(node[n])):
        node[node[n][i]][0]+=node[n][0]
        flow(node[n][i])

flow(1)
# print(ans)

ans2=ans[1:]
# print(ans2)
print(" ".join(map(str,ans2)))

Submission status: Runtime Error

Solution code:
n, q = map(int, input().split())
tl = [list() for _ in range(n)]
ans = [0] * n

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

def rec(p, x):
    ans[p-1] += x
    for num in tl[p-1]:
        rec(num, x)

for i in range(q):
    p, x = map(int, input().split())
    rec(p, x)

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

Submission status: Runtime Error

Solution code:
tmp = list(map(int, input().split()))
N, Q = tmp[0], tmp[1]

import numpy as np


tree = np.zeros([N,N])

for i in range(N-1):
    tmp = list(map(int, input().split()))
    tree[tmp[0]-1,tmp[1]-1] = 1

point = np.zeros([N])
for i in range(Q):
    q = list(map(int, input().split()))
    q_tmp = np.where(tree[(q[0]-1):,:] == 1)
   
    for j in q_tmp[1]:
        point[j] += q[1]
    point[q[0]-1] += q[1] 

point = point.tolist()
print(point)

Submission status: Runtime Error

Solution code:
import numpy as np

temp=list(map(int, input().split()))
N=temp[0]
Q=temp[1]

matrix=np.zeros((N, N))
for i in range(N):
  matrix[i, i]=1

for i in range(N-1):
  temp=list(map(int, input().split()))
  matrix[int(temp[0]-1), int(temp[1]-1)]=1
  
index=int(N-1)
while index>=0:
  matrix[index, :]+=np.sum(matrix*matrix[index, :].reshape(-1, 1), axis=0)
  index-=1
  
matrix[matrix>0]=1

counter=np.zeros(N)
for i in range(Q):
  temp=list(map(int, input().split()))
  counter+=matrix[int(temp[0]-1), :]*temp[1]
  
print(' '.join(map(str, map(int, counter.tolist()))))

Submission status: Runtime Error

Solution code:
from collections import defaultdict

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

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

seen = [False] * (N + 1)
subtree = [[] for _ in range(N + 1)]


def dfs(e, v):
    seen[v] = True
    for next_v in e[v]:
        if seen[next_v]:
            continue
        else:
            dfs(e, next_v)
            subtree[v].extend(subtree[next_v])

    subtree[v].append(v)


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


for i in q:
    for j in subtree[i]:
        ans[j] += q[i]

print(*ans[1:])

Submission status: Runtime Error

Solution code:
def D():
    def stdin():
        return map(int, input().split())

    N, Q = stdin()

    # vertexes list contained in the ith subtree root
    tree = [[] for _ in range(N)]

    for i in range(N-1):
        a, b = stdin()
        tree[a-1].append(b-1)

    counter = [0 for _ in range(N)]

    def dfs(counter, p, x):
        counter[p] += x

        vertexes = tree[p]
        for v in vertexes:
            dfs(counter, v, x)

    for i in range(Q):
        p, x = stdin()
        dfs(counter, p-1, x)

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


if __name__ == '__main__':
    D()

Submission status: Runtime Error

Solution code:

N,Q = (int(i) for i in input().split())
hen = []
value = [0] * N
for _ in range(0,N):
    hen.append([])
for i in range(0,N-1):
    a,b = (int(i) for i in input().split())
    hen[a-1].append(b)

def add(p,x,hen,value):
    value[p-1] = value[p-1] + x
    for i in hen[p-1]:
        add(i,x,hen,value)

for i in range(0,Q):
    p,q = (int(i) for i in input().split())
    add(p,q,hen,value)
print(' '.join(map(str,value)))

Submission status: Runtime Error

Solution code:
def find(a, b, neigh, ans) :
    if a in neigh :
        for v in neigh[a] :
            ans[v - 1] += b
        ans = find(v, b, neigh, ans)
        return ans
    else :
        return ans

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

neigh = {}

for i in range(n - 1) :
    neigh.setdefault(ab[i][0], []).append(ab[i][1])

ans = [0] * n
#print(neigh)

for i in range(q) :
    if px[i][0] in neigh :
        for e in neigh[px[i][0]] :
            ans[e - 1] += px[i][1]
            ans = find(e, px[i][1], neigh, ans)
            '''
            if e in neigh :
                for v in neigh[e] :
                    ans[v - 1] += px[i][1]
            '''
    ans[px[i][0] - 1] += px[i][1]

print(*ans)

Submission status: Runtime Error

Solution code:
n, q = [int(x) for x in input().split()]

t = dict()

for _ in range(n-1):
  a, b = [int(x) for x in input().split()]
  if a in t:
    t[a].add(b)
  else:
    t[a] = set([b])
s = dict()

def d(a):
  s[a] = set([a])
  if a in t:
    for i in t[a]:
      d(i)
      for j in s[i]:
      	s[a].add(j)
        
d(1)
c = {(x+1):0 for x in range(n)}
for _ in range(q):
  p, x = [int(x) for x in input().split()]
  for i in s[p]:
    c[i] += x
for i in range(n):
  print(c[i+1], end='')
  if (i != n-1):
    print(' ', end='')

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import numpy as np

def forward(matrix, plus, pos):

    for i in range(pos+1,N):
        val = matrix[pos,i]
        if val == 1:
            counter[i] += plus
            save = pos
            pos = i
            forward(matrix, plus, pos)
            pos = save


if __name__ == '__main__':
    N, Q = map(int, input().split())


    matrix = np.zeros((N,N))
    counter = []
    for i in range(N):
        counter.append(0)

    #A, B = [], []
    for i in range(N-1):
        a, b = map(int, input().split())
        matrix[a-1, b-1] = 1

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

    for p, x in zip(P,X):
        counter[p] += x
        forward(matrix, x, p)

    out = str(counter[0])
    for i in range(len(counter)-1):
        out = out + ' ' + str(counter[i+1])

    print(out)

Submission status: Runtime Error

Solution code:
def C():
    N = int(input())
    values = list(map(int, input().split()))

    values = sorted(values, reverse=True)
    weights = [(1/2)**(i+1) for i in range(N-1)] + [(1/2)**(N-1)]

    total_value = sum([values[i]*weights[i] for i in range(N)])

    print(total_value)


def D():
    def stdin():
        return map(int, input().split())

    N, Q = stdin()

    # vertexes list contained in the ith subtree root
    tree = [[] for _ in range(N)]

    for i in range(N-1):
        a, b = stdin()
        tree[a-1].append(b-1)

    counter = [0 for _ in range(N)]

    def dfs(counter, p, x):
        counter[p] += x

        vertexes = tree[p]
        for v in vertexes:
            dfs(counter, v, x)

    for i in range(Q):
        p, x = stdin()
        dfs(counter, p-1, x)

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


if __name__ == '__main__':
    D()

Submission status: Runtime Error

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



N, Q = map(int,input().split())
Node = []
Parsed = []
Counter = [0] * N
for i in range(N):
    Node.append([])
    Parsed.append([])

def parse(i):
    Parsed[i] += Node[i]
    for c in Node[i]:
        Parsed[i] += parse(c)
    #end for
    return Parsed[i]
        
for i in range(N-1):
    a, b = map(int,input().split())
    Node[a-1].append(b-1)
parse(0)
for i in range(N):
    Parsed[i].append(i)


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

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

Submission status: Runtime Error

Solution code:
class Node:
    def __init__(self, num):
        self.children = []
        self.num = num
        self.score = 0

    def add_child(self, node):
        self.children.append(node)

    def add_score(self, score):
        self.score += score


class Tree:
    @classmethod
    def find_node(cls, node, num):
        if node.num == num:
            return node
        for n in node.children:
            result = cls.find_node(n, num)
            if result:
                return result
        return None

    @classmethod
    def add_score(cls, node, score):
        node.add_score(score)
        for n in node.children:
            cls.add_score(n, score)

N, Q = map(int, input().split())
A = [0] * N
B = [0] * N
for i in range(1, N):
    A[i], B[i] = map(int, input().split())

P = [0] * (Q+1)
X = [0] * (Q+1)
for i in range(1, Q+1):
    P[i], X[i] = map(int, input().split())

root = Node(1)
for i in range(1, N):
    node = Tree.find_node(root, A[i])
    node.add_child(Node(B[i]))

for i in range(1, Q+1):
    node = Tree.find_node(root, P[i])
    Tree.add_score(node, X[i])

for i in range(1, N+1):
    node = Tree.find_node(root, i)
    print(node.score, end=' ')

Submission status: Runtime Error

Solution code:
# A, B = [int(i) for i in input().split(" ")]
# A = int(input())
# As = [int(i) for i in input().split(" ")]
# Ss = ["".join(sorted(input())) for _ in range(N)]
# from math import factorial
# def nCr(n, r): return factorial(n) // factorial(r) // factorial(n - r)
from collections import defaultdict 

N, Q = [int(i) for i in input().split(" ")]
edges = defaultdict(list)
for _ in range(N - 1):
    a, b = [int(i) for i in input().split(" ")]
    edges[a-1].append(b-1)
PX = defaultdict(int)
for _ in range(Q):
    p, x = [int(i) for i in input().split(" ")]
    PX[p-1] += x

ans = [0 for _ in range(N)]
visited = {}
def dfs(i, v):
    if i in visited:
        return
    visited[i] = True
    ans[i] += v
    for j in edges[i]:
        dfs(j, v + PX[j])
dfs(0, PX[0])
for a in ans:
    print(a, end=" ")

Submission status: Runtime Error

Solution code:
class Node:
    def __init__(self, data): #コンストラクタ
        self.data = data 
        self.kodomo = []
        self.cnt = 0

def saiki(target,tasu):
  #target = array[]
  target.cnt += tasu
  for ko in target.kodomo:
    saiki(array[ko],tasu)
  
        
n, q = [int(i) for i in input().split()]
array=[]

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

#でばっぐ
#for i in range(n):
#  print(array[i].kodomo)
  
  
for i in range(q):
  x, tasu = [int(i) for i in input().split()]
  saiki(array[x-1],tasu)
  
for i in range(n):
  if i != n-1:
    print(array[i].cnt, end =" ")
  else:
    print(array[n-1].cnt)

Submission status: Runtime Error

Solution code:
import sys
import collections


def main():
    [n, q] = [int(s) for s in sys.stdin.readline().strip().split()]
    a = [-1] * (n-1)
    b = [-1] * (n-1)
    tree = collections.defaultdict(set)
    for i in range(n-1):
        a[i], b[i] = [int(s) for s in sys.stdin.readline().strip().split()]
        tree[a[i]-1].add(b[i]-1)

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

    results = [0] * n

    def rec_add(node, cur):
        cur += adds[node]
        results[node] = cur
        for child in tree[node]:
            rec_add(child, cur)

    rec_add(0, 0)
    print(' '.join([str(n) for n in results]))


main()

Submission status: Runtime Error

Solution code:
def tree_add(tree, p, ans, num):
    ans[p] += num
    if tree[p][0] == 0 and tree[p][1] == 0:
        return
    if tree[p][0] != 0:
        tree_add(tree, tree[p][0], ans, num)
    if tree[p][1] != 0:
        tree_add(tree, tree[p][1], ans, num)

n, q = map(int, input().split())
tree = [[0, 0] for i in range(n)]
ans = [0] * n

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

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

print(*ans)

Submission status: Runtime Error

Solution code:
n,q = map(int,input().split())
ab = [[int(v) for v in input().split()] for _ in range(n-1)]
px = [[int(v) for v in input().split()] for _ in range(q)]

adjacent_list = [[] for _ in range(n+1)]

n_num = [0 for _ in range(n+1)]

q_num = [0 for _ in range(n+1)]

for query in px:
    p,x = query
    q_num[p] += x

for edge in ab:
    a,b = edge
    adjacent_list[a].append(b)

def dfs(cur,prev_state):
    now_state = q_num[cur] + prev_state
    n_num[cur] = now_state

    for next_node in adjacent_list[cur]:
        dfs(next_node,now_state)

dfs(1,0)

for ans in n_num[1:]:
    print(ans,end=' ')
print()

Submission status: Runtime Error

Solution code:
n, q = map(int, input().split())
# [[parents]]
tree = [[] for _ in range(n)]
for _ in range(n-1):
  a, b = map(int, input().split())
  if a == 1:
    tree[b-1] = [1]
  elif b == 1:
    tree[a-1] = [1]
  
  elif len(tree[a-1]) == 0:
    tree[a-1] = tree[b-1].copy()
    tree[a-1].append(b)
  elif len(tree[b-1]) == 0:
    tree[b-1] = tree[a-1].copy()
    tree[b-1].append(a)

tr = [[] for _ in range(n)]
for i, row in enumerate(tree):
  for x in row:
    tr[x].append(i+1)

cnt = [0 for _ in range(n)]
for _ in range(q):
  p, x = map(int, input().split())
  cnt[p-1] += x
  for child in tr[p]:
    cnt[child-1] += x
print(' '.join(map(str, cnt)))

Submission status: Runtime Error

Solution code:
# D


def add_value(p, x):
    value[p]+=x
    if p in data:
        for key in data[p]:
            add_value(key, x)

N, Q = map(int, input().split())
a=[]
b=[]

data = {}
for i in range(N-1):
    a, b = map(int, input().split())
    if not (a in data):
        data[a] = []
    data[a].append(b)
p = []
x = []
for i in range(Q):
    p_tmp, x_tmp = map(int, input().split())
    p.append(p_tmp)
    x.append(x_tmp)

value = {}
for i in range(1, N+1):
    value[i]=0

for i in range(len(p)):
    p_tmp = p[i]
    x_tmp = x[i]
    add_value(p_tmp, x_tmp)

for i in value.values():
    print("{} ".format(i), end="")

Submission status: Runtime Error

Solution code:
N, Q = (int(v) for v in input().split())
edge_dict = {}
for i in range(1, N):
    a, b = (int(v) for v in input().split())
    edge_dict.setdefault(a, []).append(b)
p_list, x_list = [0], [0]
for i in range(1, Q + 1):
    p, x = (int(v) for v in input().split())
    p_list.append(p)
    x_list.append(x)


def get_children(p):
    child_list = []
    for q in edge_dict.get(p, []):
        child_list.append(q)
        child_list.extend(get_children(q))
    return child_list


child_dict = {}
for p in range(1, N + 1):
    child_dict[p] = get_children(p)

cnt_dict = {}
for p, x in zip(p_list[1:], x_list[1:]):
    cnt_dict[p] = cnt_dict.get(p, 0) + x
    for child in child_dict.get(p, []):
        cnt_dict[child] = cnt_dict.get(child, 0) + x

for p in range(1, N):
    print(cnt_dict.get(p, 0), end=' ')
print(cnt_dict.get(N, 0))

Submission status: Runtime Error

Solution code:
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

def calc(p, x, li, ans):
    ans[p] += x
    s = li[p]
    for b in s:
        #print(b)
        #print(ans)
        calc(b, x, li, ans)

n, q = na()
li = [[] for i in range(n+1)]
ans = [0 for i in range(n+1)]
for i in range(n-1):
    a, b = na()
    li[a].append(b)

for i in range(q):
    p, x = na()
    #print(p,x)
    calc(p, x, li, ans)
ans.pop(0)
print(*ans)

Submission status: Runtime Error

Solution code:

import sys
sys.setrecursionlimit(1000000000)
NQ = input().split(' ')
N = int(NQ[0])
Q = int(NQ[1])

tree_dict = {
    1: {
        'count': 0,
        'has_trees': []
    }
}

def f(p,x):
    tree_dict[p]['count'] += x
    for num in tree_dict[p]['has_trees']:
        f(num,x)


#Make tree dict
for _ in range(N-1):
    ab = input().split(' ')
    a = int(ab[0])
    b = int(ab[1])
    tree_dict[a]['has_trees'].append(b)
    if b not in tree_dict.keys():
        tree_dict[b] = {
                'count': 0,
                'has_trees': []
            }

for _ in range(Q):
    px = input().split(' ')
    p = int(px[0])
    x = int(px[1])
    f(p,x)

out_put_list = []
for each_dict in tree_dict.values():
    out_put_list.append(str(each_dict['count']))
print(' '.join(out_put_list))

Submission status: Runtime Error

Solution code:
from collections import defaultdict

def f(tree, counter, p, x):
    counter[p-1] += x
    for i in tree[p-1]:
        f(tree, counter, i, x)

def main():
    N,Q=map(int, input().split())
    P=[]
    X=[]
    T = defaultdict(list)
    C = defaultdict(int)
    for i in range(N-1):
        a,b=map(int, input().split())
        T[a-1].append(b)
    for i in range(Q):
        p,x=map(int, input().split())
        P.append(p)
        X.append(x)

    for p,x in zip(P,X):
        f(T,C,p,x)

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

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import numpy as np

L = []
T = []

def InputToInt():
    A = input().split()
    for i in range(len(A)):
        A[i] = int(A[i])
    return A


def setTree(branch):
    T[branch].add(branch)
    for n in L[branch]:
        if not n in T[branch]:
            T[n] = set() | T[branch]
            setTree(n)


if __name__ == '__main__':
    N, Q = InputToInt()    
    for i in range(N):
        L.append(set())
        T.append(set())
    
    for i in range(N-1):
        a, b = InputToInt()
        L[a-1].add(b-1)
        L[b-1].add(a-1)

    setTree(0)
    
    S = np.zeros(N)
    for i in range(Q):
        p, x = InputToInt()
        for j in range(N):
            if p-1 in T[j]:
                S[j] += x

    for i in range(N):
        print(S[i], end = ' ')

Submission status: Runtime Error

Solution code:
import sys
import queue

def resolve():
    N, Q = map(int, input().split())
    nodes = [[] for _ in range(N)]
    counter = [0] * (N)

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

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

    def send(numNode):
        for target in nodes[numNode]:
            counter[target] += counter[numNode]
            send(target)

    send(0)

    for count in counter:
        print(count, end=" ")

    print("")


if __name__ == "__main__":
    resolve()

Submission status: Runtime Error

Solution code:
tmp = list(map(int, input().split()))
N, Q = tmp[0], tmp[1]

import numpy as np


tree = np.zeros([N,N])

for i in range(N-1):
    tmp = list(map(int, input().split()))
    tree[tmp[0]-1,tmp[1]-1] = 1

point = np.zeros([N])
for i in range(Q):
    q = list(map(int, input().split()))
    q_tmp = np.where(tree[(q[0]-1):,:] == 1)
   
    for j in q_tmp[1]:
        point[j] += q[1]
    point[q[0]-1] += q[1] 

print(point)

Submission status: Runtime Error

Solution code:
# A, B = [int(i) for i in input().split(" ")]
# A = int(input())
# As = [int(i) for i in input().split(" ")]
# Ss = ["".join(sorted(input())) for _ in range(N)]
# from math import factorial
# def nCr(n, r): return factorial(n) // factorial(r) // factorial(n - r)
from collections import defaultdict 

N, Q = [int(i) for i in input().split(" ")]
edges = defaultdict(list)
for _ in range(N - 1):
    a, b = [int(i) for i in input().split(" ")]
    edges[a-1].append(b-1)
PX = defaultdict(int)
for _ in range(Q):
    p, x = [int(i) for i in input().split(" ")]
    PX[p-1] += x

ans = [0 for _ in range(N)]
def dfs(i, v):
    if 0 <= i < N:
        ans[i] += v
    for j in edges[i]:
        dfs(j, v + PX[j])
dfs(0, PX[0])
for a in ans:
    print(a, end=" ")

Submission status: Runtime Error

Solution code:
N,Q = map(int,input().split())
ab = [list(map(int,input().split())) for _ in range(N-1)]
px = [list(map(int,input().split())) for _ in range(Q)]
p_apply = [[] for i in range(N)]
counter = [0] * N

def PlusCounter(p):
    if len(p_apply[p-1]) != 0:
        for number in p_apply[p-1]:
            counter[number-1] += x
            PlusCounter(number)

for a,b in ab:
    p_apply[a-1].append(b)

for p,x in px:
    counter[p-1] += x
    PlusCounter(p)

print(*counter)

Submission status: Runtime Error

Solution code:

NQ = input().split(' ')
N = int(NQ[0])
Q = int(NQ[1])

tree_dict = {
    1: {
        'count': 0,
        'has_trees': []
    }
}

def f(p,x):
    tree_dict[p]['count'] += x
    for num in tree_dict[p]['has_trees']:
        f(num,x)


#Make tree dict
for _ in range(N-1):
    ab = input().split(' ')
    a = int(ab[0])
    b = int(ab[1])
    tree_dict[a]['has_trees'].append(b)
    if b not in tree_dict.keys():
        tree_dict[b] = {
                'count': 0,
                'has_trees': []
            }

for _ in range(Q):
    px = input().split(' ')
    p = int(px[0])
    x = int(px[1])
    f(p,x)

out_put_list = []
for each_dict in tree_dict.values():
    out_put_list.append(str(each_dict['count']))
print(' '.join(out_put_list))

Submission status: Runtime Error

Solution code:
n,q=map(int,input().split())
ki=[[] for i in range(n+1)]
#ki[0]="null"

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

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


ans=[0 for i in range(n+1)]
#ans[0]="null"
point=0

ed=[]

def tansa(n,point):
    global ed
    point+=scores[n]
    ed.append(n)
    for p in ki[n]:
        if not p in ed:
            tansa(p,point)
    else:
        ans[n]=point
        
tansa(1,0)

ans=ans[1:]
ans=[str(i) for i in ans]
print(" ".join(ans))

Submission status: Runtime Error

Solution code:
n, q = map(int, input().split())
tree = [[] for _ in range(n+1)]
for _ in range(n-1):
    a, b = map(int, input().split())
    tree[a].append(b)
adds = [0]*(n+1)
for _ in range(q):
    p, x = map(int, input().split())
    adds[p] += x

res = [0]*(n+1)

def add_x(p, x):
    res[p] += x
    for child in tree[p]:
        add_x(child, x)

for i in range(1, n+1):
    add_x(i, adds[i])

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

Submission status: Runtime Error

Solution code:
def get_verteces_in_subtree(vertex):
    children = tree_dictionary[vertex]
    if len(children) == 0:
        return [vertex]
    return [vertex] + sum([get_verteces_in_subtree(child) for child in children], [])

N, Q = list(map(int, input().split()))
edges = [list(map(int, input().split())) for _ in range(N-1)]
operations = [list(map(int, input().split())) for _ in range(Q)]

tree_dictionary = {i: [] for i in range(1, N+1)}
for edge in edges:
    tree_dictionary[edge[0]].append(edge[1])

counts = [0] * N
for op in operations:
    top_vertex, value = op
    added_verteces = get_verteces_in_subtree(top_vertex)
    for v in added_verteces:
        counts[v-1] += value

output = ""
for c in counts:
    output += (str(c) + " ")
output = output[:-1]
print(output)

Submission status: Runtime Error

Solution code:
def D():
    def stdin():
        return map(int, input().split())

    N, Q = stdin()

    # vertexes list contained in the ith subtree root
    tree = [[] for _ in range(N)]

    for i in range(N-1):
        a, b = stdin()
        tree[a-1].append(b-1)

    counter = [0 for _ in range(N)]

    def dfs(counter, p, x):
        counter[p] += x

        vertexes = tree[p]
        for v in vertexes:
            dfs(counter, v, x)

    for i in range(Q):
        p, x = stdin()
        dfs(counter, p-1, x)

    print(counter)


if __name__ == '__main__':
    D()

Submission status: Runtime Error

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

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

ans = [0 for _ in range(n)]
def f(r, y):
    for j in root[r]:
        ans[j] += y
        # print(ans)
        s = j
        f(s, y)

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

ans = map(str, ans)
print(" ".join(ans))

Submission status: Runtime Error

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

tree = [[] for _ in range(n)]
ret=[0]*n

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

def counter(target,num):
    global ret
    ret[target]+=num
    if not tree[target]:
        return
    for i in tree[target]:
        counter(i,num)
for _ in range(q):
    p,x=map(int,input().split())
    counter(p-1,x)

print(*ret)