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:
node_len, ope_count = [int(x) for x in input().split()]

node_path = {}
node_weight = {}

for i in range(node_len-1):
    parent, child = input().split()

    if i == 0:
        node_path[parent] = [parent]
        node_weight[parent] = 0

    if child not in node_path:
        node_path[child] = []
        node_weight[child] = 0
        if parent in node_path:
            node_path[child] = node_path[parent] + [child]

for i in range(ope_count):
    node_id, weight = input().split()
    node_weight[node_id] += int(weight)

for i in range(node_len):
    node_id = str(i + 1)
    value = sum([node_weight[id] for id in node_path[node_id]])
    print(value)

Submission status: Runtime Error

Solution code:

N, Q = 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)]

edge_map = {}
for i in range(N):
    edge_map[i+1] = []

for edge in edges:
    a = edge[0]
    b = edge[1]
    edge_map[a].append(b)
    edge_map[b].append(a)

counters_map = [None for i in range(N)]

def dfs(idx, parent):
    global counters_map
    if counters_map[idx - 1]:
        return counters_map[idx - 1]
    counter = [idx]
    for child in edge_map[idx]:
        if parent and child == parent:
            continue
        counter.extend(dfs(child, idx))
    counters_map[idx-1] = counter
    return counter

dfs(1, None)

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

for operation in operations:
    p = operation[0]
    x = operation[1]
    for idx in counters_map[p-1]:
        counters[idx-1] += x

print(counters)

Submission status: Runtime Error

Solution code:
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:
from collections import defaultdict, Counter
def increment(key, count, adj_list, inc_num, visited):
    if key in visited:
        return
    count[key] += inc_num
    visited.add(key)
    for num in adj_list[key]:
        increment(num, count, adj_list, inc_num, visited)

N, Q = map(int, input().split())
adj_list = defaultdict(list)
count = Counter()

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

for i in range(Q):
    c, d = map(int, input().split())
    increment(c, count, adj_list, d, set([]))

print(' '.join([str(num) for num in count.values()]))

Submission status: Runtime Error

Solution code:
from sys import stdin

ntree = []
ans = []


def culceach(n, sum):
    ans[n-1] += sum
    for i in range(len(ntree[n-1])):
        culceach(ntree[n-1][i], ans[n-1])

def addnum(p, x):
    ans[p-1] += x

#    for i in range(len(ntree[p-1])):
#        addnum(ntree[p-1][i], x)

n, q = [int(x) for x in stdin.readline().rstrip().split()]

for i in range(n):
    ntree.append([])
    ans.append(0)

for i in range(n-1):
  a, b = [int(x) for x in stdin.readline().rstrip().split()]
  ntree[a-1].append(b)

for i in range(q):
  p, x = [int(x) for x in stdin.readline().rstrip().split()]
  addnum(p,x)

culceach(1, 0)

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

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)
    e[b].append(a)

q = []
for i in range(Q):
    p, x = map(int, input().split())
    q.append((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[0]]:
        ans[j] += i[1]

print(*ans[1:])

Submission status: Runtime Error

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

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

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

trace = []


def rec(pos, parent):
    trace.append(pos)
    children = tree[pos]
    for child in children:
        if child == parent:
            continue
        rec(child, pos)


rec(0, -1)


def rec2(pos, parent, count):
    counter[pos] += sousa[pos] + count
    children = tree[pos]
    for child in children:
        if child == parent:
            continue
        rec2(child, pos, sousa[pos]+count)


rec2(0, -1, 0)

print(" ".join(str(i) for i in counter))

Submission status: Runtime Error

Solution code:
from collections import defaultdict


def dfs(to, fr, score):
    score += scores[to]
    ans[to] = score
    for u in adjacent[to]:
        if u == fr:
            continue
        dfs(u, to, score)


N, Q = map(int, input().split())
adjacent = defaultdict(list)
for i in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    adjacent[a].append(b)
    adjacent[b].append(a)
scores = [0] * N
for i in range(Q):
    p, x = map(int, input().split())
    p -= 1
    scores[p] += x

ans = [0] * N
dfs(0, -1, 0)
print(' '.join([str(ans[i]) for i in range(N)]))

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
A = [''] * (N+1)
C = [0] * (N+1)
for i in range(N-1):
  a, b = map(int, input().split())
  if len(A[a]) == 0:
    A[a] = [b]
  else:
    A[a].append(b)
def AddPX(n, x):
  C[n] += x
  for i in A[n]:
    AddPX(i, x)
  
for i in range(Q):
  p, x = map(int, input().split())
  AddPX(p, x)

print (" ".join(map(str, C[1:])))

Submission status: Runtime Error

Solution code:
n,q=map(int,input().split())
tree = [set() for _ in range(n)]
for i in range(n-1):
    a,b=map(int,input().split())
    tree[a-1].add(b)
#print(tree)

ans=[0]*n
def add_l(x,l):
    if tree[x]:
        for i in list(tree[x]):
            add_l(i-1,l)
        l.extend(list(tree[x]))

for i in range(q):
    
    p,x=map(int,input().split())
    add_list=[p]
    add_l(p-1,add_list)

    #print(add_list)
    for add in add_list:
        ans[add-1]+=x
print(*ans)

Submission status: Runtime Error

Solution code:
from collections import defaultdict, Counter
def increment(key, count, adj_list, inc_num):
    count[key] += inc_num
    for num in adj_list[key]:
        increment(num, count, adj_list, inc_num)

N, Q = map(int, input().split())
adj_list = defaultdict(list)
count = Counter()

for i in range(N-1):
    a, b = map(int, input().split())
    adj_list[a].append(b)
for i in range(Q):
    c, d = map(int, input().split())
    increment(c, count, adj_list, d)

print(' '.join([str(num) for num in count.values()]))

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
tree = [[] for i in range(N)]
for i in range(N-1):
    ai, bi = map(int, input().split())
    ai -= 1
    bi -= 1
    tree[ai].append(bi)
point = [0] * N
for j in range(Q):
    pi, xi = map(int, input().split())
    pi -= 1
    point[pi] = point[pi] + xi

print(tree)
print(point)

answer = [0] * N
def dfs(node, p):
    answer[node] = p + point[node]
    for t in tree[node]:
        dfs(t, answer[node])
    return None

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

Submission status: Runtime Error

Solution code:
import numpy as np

n, q = map(int, input().split())
g = np.zeros((n+1,n+1))

ans = np.zeros((n)) #Do not Foget -1


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

#for i in range(n+1):
#    print(g[0])


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

    stack = []
    ans[q-1] += x
    for i in range(n+1):
        if g[q][i] == 1:
            stack.append(i)

    while len(g) > 0:
        if len(stack) <= 0:
            break
        p = stack.pop(-1)
        #print(p)
        ans[p-1] += x
        for i in range(n+1):
            if g[p][i] == 1:
                stack.append(i)
ans_str = str(ans.astype(int))
ans_str = ans_str.replace('[','').replace(']','')
print(ans_str)

Submission status: Runtime Error

Solution code:
def adx(p,oya,tox,total):
  tox[p] += total
  total = tox[p]
  if(len(oya[p]) == 0):
    return 0

  else:
    for i in oya[p]:
      adx(i,oya,tox,total)

  return 0

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

oya = [ [] for i in range(n + 1)]
tox = [0 for i in range(n + 1)]

hit = list(range(1,n+1))

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

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


adx(1,oya,tox,0)

tox.pop(0)

print(*tox)

Submission status: Runtime Error

Solution code:
class Node:
  def __init__(self, n):
    self.number = n
    self.children = []
    self.value = 0
def add_values(nodes, i, x):
  n = nodes[i]
  n.value += x
  for c in n.children:
    add_values(nodes, c, x)
n, q = map(int, input().split())
nodes = [Node(i) for i in range(0, n + 1)]
nodes[0] = None
for i in range(n - 1):
  a, b = map(int, input().split())
  nodes[a].children.append(b)
for _ in range(q):
  p, x = map(int, input().split())
  add_values(nodes, p, x)
print(' '.join(str(nodes[i].value) for i in range(1, n + 1)))

Submission status: Runtime Error

Solution code:
from collections import defaultdict


def p_d_r(ans, l, R, x):
    for i in R:
        ans[i - 1] += x
        p_d_r(ans, l, l[i], x)


def p_d():
    N, Q = map(int, input().split())
    l = defaultdict(list)
    ans = [0] * N

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

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

    print(*ans)


if __name__ == '__main__':
    p_d()

Submission status: Runtime Error

Solution code:
N, Q = map(int, raw_input().split())
tree = [set() for i in range(N)]
ans = [0 for i in range(N)]


def func(_x, _p):
    ans[_x-1] += _p
    for x in tree[_x-1]:
        func(x, _p)


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

for i in range(0, Q):
    v, p = map(int, raw_input().split())
    func(v, p)

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

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, x = [0], [0]
for i in range(1, Q + 1):
    pi, xi = (int(v) for v in input().split())
    p.append(pi)
    x.append(xi)


def add_count(p, x):
    cnt_dict[p] = cnt_dict.get(p, 0) + x
    for q in edge_dict.get(p, []):
        add_count(q, x)


cnt_dict = {}
for p, x in zip(p[1:], x[1:]):
    add_count(p, 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:
n, q = [int(x) for x in input().split()]

tree = [[] for _ in range(n + 1)]
cnt = [0] * (n + 1)

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

def walk(p, x):
    cnt[p] += x
    for n in tree[p]:
        walk(n, x)

for _ in range(q):
    p, x = [int(x) for x in input().split()]
    walk(p, x)

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

Submission status: Runtime Error

Solution code:
N,Q = map(int,input().split())
ab_list = [tuple(map(int,input().split())) for _ in range(N-1)]
px_list = [tuple(map(int,input().split())) for _ in range(Q)]

px_dict = {}
for p, x in px_list:
    if p in px_dict:
        px_dict[p] += x
    else:
        px_dict[p] = x

ab_dict = {}
for a,b in ab_list:
    if a in ab_dict:
        ab_dict[a].append(b)
    else:
        ab_dict[a] = [b]

scores = [0 for _ in range(N+1)] # 1子おおい

def add_cnt(v, score):
    # pxdictから持ってきてスコアを足す
    if v in px_dict:
        score += px_dict[v]
    # スコアを足さないこともある
    
    #今いる頂点に現在のスコアをめも
    scores[v] = score
    
    # 繋がっている頂点に今のスコアを投げる
    if v in ab_dict:
        for b in ab_dict[v]:
            add_cnt(b,score)

add_cnt(1,0)

print(" ".join(map(str,scores[1:])))

Submission status: Runtime Error

Solution code:
n,q=map(int,input().split())
box=[list(map(int,input().split())) for i in range(n-1)]
point=[list(map(int,input().split())) for i in range(q)]
tree={i+1:[] for i in range(n)}
answer=[0]*n
for x,y in box:tree[x] +=[y]

def tree_sum(tree,point_x,point_y):
    answer[point_x-1] +=point_y
    for i in tree[point_x]:
        if len(tree[i])!=0:
            tree_sum(tree,i,point_y)
        else:answer[i-1] +=point_y
    return tree
for x,y in point:
    tree_sum(tree,x,y)

print(*answer)

Submission status: Runtime Error

Solution code:
n,q=map(int,input().split())
d = {}
ans = [0]*(n+1)
for i in range(n-1):
    sta,gol = map(int,input().split())
    if sta not in d:
        d[sta] = set() 
    d[sta].add(gol)

#print(d)
    
def cal_(ans_,sta_,val_):
    ans_[sta_]+=val_
    if sta_ in d:
        targetset = d[sta_]
        for t in targetset:
            ans_ = cal_(ans_,t,val_)
    return ans_

for i in range(q):
    sta,val = map(int,input().split())
    ans = cal_(ans,sta,val)
    
for i in range(n):
    print(ans[i+1], " ",end="")

Submission status: Runtime Error

Solution code:
import collections
N,Q=map(int,input().split())
A,B=[],[]
for i in range(N-1):
    a,b = map(int,input().split())
    A.append(a)
    B.append(b)
P,X=[],[]
for j in range(Q):
    p,x = map(int,input().split())
    P.append(p)
    X.append(x)

#print(list(zip(A,B)))
#print(list(zip(P,X)))


fts=collections.defaultdict(set)

#make links
for a, b in zip(A,B):
    fts[a].add(b)


counters = [0] * N

def add_points(p,x):
#    print(str(p)+','+str(x))
    if len(fts[p])==0:
        counters[p-1] += x
    else:
        counters[p-1] += x
        for a in fts[p]:
            add_points(a,x)

#calc points
for p,x in zip(P,X):
    add_points(p,x)
#    print(counters)

for c in counters:
    print(str(c)+' ',end='')
print()

Submission status: Runtime Error

Solution code:
import sys,heapq,math,resource
from collections import deque,defaultdict
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
DBG = True # and False
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

def setrlim():
  sys.setrecursionlimit(250000)
  soft,hard = resource.getrlimit(RLIMIT_STACK)
  # setrlimit works on ubuntu (and atcoder), but not on WSL
  resource.setrlimit(RLIMIT_STACK, (128*1024*1024,hard))

def dfs(i,fromup):
    y[i] = fromup + v[i]
    for d in dst[i]:
        dfs(d,y[i])

n,q = inm()
dst = [ [] for i in range(n) ]
for i in range(n-1):
    a,b = inm()
    a -= 1
    b -= 1
    dst[a].append(b)
v = [0]*n
for i in range(q):
    p,x = inm()
    p -= 1
    v[p] += x
y = [0]*n
dfs(0,0)
for i in range(n):
    printn((' ' if i>0 else '') + str(y[i]))
print("")

Submission status: Runtime Error

Solution code:
class Node:
    def __init__(self, key):
        self.key = key
        self.child = []
        self.point = 0

n, q = map(int, input().split())
a, b, p, x = [], [], [], []
nodes = []
nodes.append(None)
ans = []

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

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

# Make node list
for i in range(1, n+1):
    node = Node(i)
    nodes.append(node)


for i in range(n-1):
    nodeParent = nodes[a[i]]
    nodeChild = nodes[b[i]]
    nodeParent.child.append(nodeChild)

def printNode(node):
#    print(node.point)
    ans.append(node.point)
    for child in node.child:
        printNode(child)

#printNode(nodes[1])

def addCount(node, point):
    node.point += point
    for child in node.child:
        addCount(child, point)

for i in range(q):
    node = nodes[p[i]]
    addCount(node, x[i])

printNode(nodes[1])

print(' '.join([str(i) for i in ans]))

Submission status: Runtime Error

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

tree = [[] for _ in range(n + 1)]
cnt = [0] * (n + 1)

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

def walk(p, x):
    cnt[p] += x
    for n in tree[p]:
        walk(n, x)

for _ in range(q):
    p, x = [int(x) for x in input().split()]
    walk(p, x)

print(*cnt[1:])

Submission status: Runtime Error

Solution code:
class Node():
    def __init__(self, next):
        if next is None:
            self.next = []
        else:
            self.next = [next]
        self.counter = 0

    def add(self, x):
        if len(self.next) != 0:
            for sn in self.next:
                sn.add(x)
        self.counter += x

n, q = map(int, input().split(' '))
nodes = [Node(None) for _ in range(0, n)]

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

for _ in range(0, q):
    p, x = map(int, input().split(' '))
    nodes[p-1].add(x)

count = 0
for node in nodes:
    count += 1
    print(node.counter, end='')
    if count != n:
        print(' ', end='')

print()

Submission status: Runtime Error

Solution code:
from collections import defaultdict
def main():

    N, Q = [int(x) for x in input().split()]
    counter = {key:0 for key in range(1, N+1)}
    tree = defaultdict(list)

    # 要は木構造っぽいものを作りたい
    for _ in range(N - 1):
        a, b = [int(x) for x in input().split()]
        tree[a].append(b)
    
    # 木構造っぽいものから答えを出す
    def add_num(key, num):
        counter[key] += num
        if key not in tree:
            return
        for new_key in tree[key]:
            add_num(new_key, num)
        
    for _ in range(Q):
        p, x = [int(x) for x in input().split()]
        add_num(p, x)

    print(" ".join([str(val) for key, val in sorted(counter.items())]))

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
n, q = [int(i) for i in input().split()]
a1 = {}
a2 = {}
for _ in range(n - 1):
    x, y = [int(i) - 1 for i in input().split()]
    if x in a1:
        a1[x].append(y)
    else:
        a1[x] = [y]
    if x in a2:
        a2[x].append(y)
    else:
        a2[x] = [y]
root = [-1] * n


def c(ind=0, ro=-1):
    global root
    if root[ind] != -1:
        return 0
    root[ind] = ro
    if ind in a1:
        for i in a1[ind]:
            c(i, ind)
    if ind in a2:
        for i in a2[ind]:
            c(i, ind)


c()
p = [0] * n
for _ in range(q):
    x, y = [int(i) for i in input().split()]
    p[x - 1] += y
r = []
for i in range(n):
    j = i
    k = 0
    while True:
        k += p[j]
        if j == -1:
            break
        j = root[j]
    r.append(str(k))
print(" ".join(r))

Submission status: Runtime Error

Solution code:
import sys

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)

    print(" ".join([str(n) for n in counter]))


if __name__ == "__main__":
    resolve()

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(100000000)

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

query = [[0] for _ in range(N)]
ans = [[0] for _ in range(N)]

for p,x in px:
    query[p-1] = query[p-1] + x
    
adj_list = [[] for _ in range(N)]
for a,b in ab:
    adj_list[a-1].append(b-1)
    adj_list[b-1].append(b-1)

memo = [True] * N

def dfs(v,val):
    child = adj_list[v]
    memo[v] = False
    val += query[v]
    ans[v] = val
    for s in child:
        if memo[s]:
            dfs(s,val)
        
dfs(0,0)
print(*ans)

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>

using namespace std;

using ll = long long;

vector<vector<int>> tree;
vector<int> v;

void up(int node, int val)
{
    v[node] += val;
    for (auto e : tree[node])
        up(e, v[node]);
    return;
}

int main() 
{
    int n, q; cin >> n >> q;
    tree = vector<vector<int>>(n, vector<int>());
    for (int i = 0; i < n - 1; i++)
    {
        int a, b; cin >> a >> b;
        tree[a - 1].push_back(b - 1);
    }
    v = vector<int>(n, 0);
    while (q--)
    {
        int p, x; cin >> p >> x;
        v[p - 1] += x;
    }
    up(0, 0);
    for (auto e : v)
        cout << e << " ";
    return 0;
}

Submission status: Runtime Error

Solution code:
import sys,heapq,math,resource
from collections import deque,defaultdict
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
DBG = True # and False
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

def setrlim():
  sys.setrecursionlimit(250000)
  soft,hard = resource.getrlimit(RLIMIT_STACK)
  # setrlimit works on ubuntu (and atcoder), but not on WSL
  #resource.setrlimit(RLIMIT_STACK, (128*1024*1024,hard))

def dfs(i,fromup):
    y[i] = fromup + v[i]
    for d in dst[i]:
        dfs(d,y[i])

n,q = inm()
dst = [ [] for i in range(n) ]
for i in range(n-1):
    a,b = inm()
    a -= 1
    b -= 1
    dst[a].append(b)
v = [0]*n
for i in range(q):
    p,x = inm()
    p -= 1
    v[p] += x
y = [0]*n
dfs(0,0)
for i in range(n):
    printn((' ' if i>0 else '') + str(y[i]))
print("")

Submission status: Runtime Error

Solution code:
from collections import defaultdict
N,Q = map(int,input().split())

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

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

def dig(i,tmp):
    tmp += adds[i]
    ans[i] = tmp
    if tree[i]:
        for v in tree[i]: dig(v,tmp)

ans = defaultdict(int)
tmp = 0
dig(1,tmp)

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

Submission status: Runtime Error

Solution code:

N, Q = map(int, input().split())
A = [[] for i in range(N)]
P = []
X = []
c = [0]*N
def add(p, x):
    for a in A[p-1]:
        c[a-1] += x
        add(a, x)

for i in range(N-1):
    a, b = map(int, input().split())
    A[a-1].append(b)
for i in range(Q):
    p, x = map(int, input().split())
    c[p-1] += x
    add(p, x)
print(' '.join(map(str,c)))

Submission status: Runtime Error

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

def main():
    N, Q = map(int, input().split())
    graph = [[] for _ in range(N)]
    for _ in range(N-1):
        a, b = map(int, input().split())
        graph[a-1].append(b-1)
        graph[b-1].append(a-1)
    PX = [list(map(int, input().split())) for _ in range(Q)]

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

    checked = [False for _ in range(N)]
    checked[0] = True
    def dfs(p, s, checked, score):
        #print(p, s, score)
        ns = s + score[p]
        score[p] += s
        for q in graph[p]:
            if not checked[q]:
                checked[q] = True
                score = dfs(q, ns, checked, score)
        return score

    ans = dfs(0, 0, checked, score)
    print(' '.join([str(a) for a in ans]))


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from collections import defaultdict

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

res = [0]*(n+1)

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

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

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

Submission status: Runtime Error

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

N, Q = map(int, input().split())
A = [[int(v) for v in input().split()] for _ in range(N - 1)]
B = [[int(v) for v in input().split()] for _ in range(Q)]

B.sort(key = lambda x:x[0])

d = [set() for i in range(N)]
score = [0] * N

for i in range(N - 1):
    x, y = A[i]
    d[x - 1].add(y - 1)

for i in range(Q):
    x, y = B[i]
    score[x - 1] += y

ans = [0] * N
def dfs(index, c):
    ans[index] = c + score[index]
    for v in d[index]:
        dfs(v, c + score[index])
    return

dfs(0, 0)
print(*ans)

Submission status: Runtime Error

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

N, Q = map(int, input().split())
A = [[int(v) for v in input().split()] for _ in range(N - 1)]
B = [[int(v) for v in input().split()] for _ in range(Q)]

B.sort(key = lambda x:x[0])

d = [set() for i in range(N)]
score = [0] * N

for i in range(N - 1):
    x, y = A[i]
    d[x - 1].add(y - 1)

for i in range(Q):
    x, y = B[i]
    score[x - 1] += y

ans = [0] * N
def dfs(index, c):
    ans[index] = c + score[index]
    for v in d[index]:
        dfs(v, c + score[index])
    return

dfs(0, 0)
print(*ans)

Submission status: Runtime Error

Solution code:
# 4 3
# 1 2
# 2 3
# 2 4
# 2 10
# 1 100
# 3 1

n, q = list(map(int, input().split(" ")))
a = []
b = []
for i in range(n-1):
    j, k = list(map(int, input().split(" ")))
    a.append(j)
    b.append(k)

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


class Node:
    def __init__(self, id):
        self.id = id
        self.counter = 0
        self.linked = []

    def add_node(self, node):
        self.linked.append(node)

    def add_count(self, count):
        self.counter += count
        for i in self.linked:
            i.add_count(count)

# make node
tree = []
for i in range(n):
    tree.append(Node(i))

for j, k in zip(a, b):
    tree[j-1].add_node(tree[k-1])

for j, k in zip(p, x):
    tree[j-1].add_count(k)

m = []
for i in tree:
    m.append(i.counter)

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

Submission status: Runtime Error

Solution code:
import sys
input=sys.stdin.readline
def Nodify(n):
    for i in graph[n]:
        if Tree[i]==-1:
            Tree[i]=n
            Nodify(i)
n,q=map(int,input().split())
graph=[[] for _ in range(n)]
for _ in range(n-1):
    a,b=map(int,input().split())
    graph[a-1].append(b-1)
    graph[b-1].append(a-1)
Tree=[-1]*n
Nodify(0)
counter=[0 for _ in range(n)]
for _ in range(q):
    p,x=map(int,input().split())
    counter[p-1]+=x
for i in range(n):
    y=i
    ret=counter[y]
    while y!=0:
        ret+=counter[Tree[y]]
        y=Tree[y]
    print(ret, end=" ")

Submission status: Runtime Error

Solution code:
import math
import fractions
import copy
import numpy as np
import heapq
def j(q):
    if q==1: print("Yes")
    elif q == 0:print("No")
    exit(0)
rem = pow(10,9)+7
"""
def ct(x,y):
    if (x>y):print("+")
    elif (x<y): print("-")
    else: print("?")
"""

def ip():
    return int(input())
def iprow():
    return [int(i) for i in input().split()]
def ips():
    return (int(i) for i in input().split())
def printrow(a):
    for i in a:
        print(i)
"""
#decomment when needed
def combinations(n,r):
    if n<r:return 0
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
def permutations(n,r):
    if n<r:return 0
    return math.factorial(n) // math.factorial(n - r)
def lcm(x, y):
    return (x * y) // fractions.gcd(x, y)
"""

def addbottom(total,tree,k,value,base):
    #print("current layer",k)
    #print(k,value)
    total[k]+=value
    #print(total)
    if len(tree[k]):
        for i in tree[k]:
            #print(k,i)
            total = addbottom(total, tree, i, value,base)
    return total


n ,m = ips()
tree = [[] for i in range(n+1)]
for i in range(n-1):
    x,y = ips()
    tree[x].append(y)
total = [0 for i in range(n+1)]
for i in range(m):
    x,adder = ips()
    total[x]+=adder
base = copy.copy(total)
for i in range(1,n):
    #print("adding up",i,base[i])
    value = base[i]
    if len(tree[i]):
        for k in tree[i]:
            total = addbottom(total,tree,k,value,base)
for i in range(1,n):
    print(total[i],end=" ")
print(total[n])

Submission status: Runtime Error

Solution code:

N, Q = map(int, input().split())
A = [[] for i in range(N)]
P = []
X = []
c = [0]*N
def add(p, x):
    for a in A[p-1]:
        c[a-1] += x
        add(a, x)

for i in range(N-1):
    a, b = map(int, input().split())
    A[a-1].append(b)
for i in range(Q):
    p, x = map(int, input().split())
    c[p-1] += x
    add(p, x)
print(c)

Submission status: Runtime Error

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

N, Q = map(int, input().split())
A = [[int(v) for v in input().split()] for _ in range(N - 1)]
B = [[int(v) for v in input().split()] for _ in range(Q)]

B.sort(key = lambda x:x[0])

d = [set() for i in range(N)]
score = [0] * N

for i in range(N - 1):
    x, y = A[i]
    d[x - 1].add(y - 1)

for i in range(Q):
    x, y = B[i]
    score[x - 1] += y

ans = [0] * N
def dfs(index, c):
    ans[index] = c + score[index]
    for v in d[index]:
        dfs(v, c + score[index])
    return

dfs(0, 0)
print(*ans)