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:
import sys
inputs = sys.stdin.readlines()

from collections import deque, defaultdict

def dfs_generator(nodes, start):
    nexts = deque([start])
    while nexts:
        node = nexts.popleft()
        nexts.extend(nodes[node]['childs'])
        yield node

nodes = dict({1: dict({'val': 0, 'childs': []})})
for x in inputs[1:n]:
    from_, to_ = map(int, x.split())
    nodes[from_]['childs'].append(to_)
    nodes[to_] = dict({'val': 0, 'childs': []})

subtree_roots = defaultdict(int)
for x in inputs[n:]:
    n, v = map(int, x.split())
    subtree_roots[n] += v
'''
subtrees = defaultdict(list)
for r, v in subtree_roots.items():
    gen = dfs_generator(nodes, r)
    try:
        while True:
            node = next(gen)
            subtrees[r].append(node) 
    except StopIteration:
        pass
    for n in subtrees[r]:
        nodes[n]['val'] += v

for i in range(1, n):
    print(str(nodes[i]['val']), end=' ')
print(str(nodes[i+1]['val']))
'''

Submission status: Runtime Error

Solution code:
N, Q = [int(i) for i in input().split(' ')]

class Node:
  def __init__(self):
    self.data = None
    self.children = []
    
  def add_child(self, child):
    self.children.append(child)
    
  def set_data(self, data):
    self.data = data
    
tree = {}
for i in range(1, N+1):
  tree[i] = Node()
  
for _ in range(N-1):
  a, b = [int(i) for i in input().split(' ')]
  tree[a].add_child(b)

for _ in range(Q):
  a, num = [int(i) for i in input().split(' ')]
  if tree[a].data:
    num += tree[a].data
  tree[a].set_data(num)

def set_num(node, num):
  if node.data:
  	num += node.data
  node.set_data(num)
  for c in node.children:
    set_num(tree[c], num)

set_num(tree[1], 0)

print(*[t.data for t in tree.values()])

Submission status: Runtime Error

Solution code:
n, q = map(int, input().split())
ans = [0 for x in range(n)]
g = [list() for x in range(n)]
for i in range (n - 1) :
    v, u = map(int, input().split())
    v -= 1
    u -= 1
    g[v].append(u)
    g[u].append(v)
for i in range (q):
    p, x = map(int, input().split())
    p -= 1;
    ans[p] += x
def dfs(v, p):
    for u in g[v]:
        if (u != p) :
            ans[u] += ans[v]
            dfs(u, v)
dfs(0, -1)
print(*ans)

Submission status: Runtime Error

Solution code:
n, q = map(int, input().split())
ans = [0 for x in range(n)]
g = [list() for x in range(n)]
for i in range (n - 1) :
    v, u = map(int, input().split())
    v -= 1
    u -= 1
    g[v].append(u)
    g[u].append(v)
for i in range (q):
    p, x = map(int, input().split())
    p -= 1;
    ans[p] += x
def dfs(v, p):
    for u in g[v]:
        if (u != p) :
            ans[u] += ans[v]
            dfs(u, v)
dfs(0, -1)
for x in ans:
    print(x, end = ' ')

Submission status: Runtime Error

Solution code:
i=lambda:map(int,input().split())
N,Q=i()
adj=[[] for _ in range(N)]
for _ in range(N-1):
  a,b=i()
  adj[a-1].append(b-1)
  adj[b-1].append(a-1)
V = [0 for _ in range(N)]
for _ in range(Q):
  p,x=i()
  V[p-1]+=x
def dfs(cur, prv):
  for nxt in adj[cur]:
    if nxt == prv: continue
    V[nxt] += V[cur]
    dfs(nxt, cur)
dfs(0,-1)
print(' '.join(map(str, V)))

Submission status: Runtime Error

Solution code:
def cnt_up(p, x):
    cnt[p] += x
    for i in child[p]:
        cnt_up(i, x)


N, Q = map(int, input().split())
child = [[] for _ in range(N)]
cnt = [0] * N
X = [0] * N
for _ in range(N-1):
    a, b = map(int, input().split())
    child[a-1].append(b-1)

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

#print(child)
#print(X)
for i in range(N):
    if X[i]:
        cnt_up(i, X[i])

print(*cnt)

Submission status: Runtime Error

Solution code:
def cnt_up(p, x):
    cnt[p] += x
    for i in child[p]:
        cnt_up(i, x)


N, Q = map(int, input().split())
child = [[] for _ in range(N)]
cnt = [0] * N
X = [0] * N
for _ in range(N-1):
    a, b = map(int, input().split())
    child[a-1].append(b-1)

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

for i in range(N):
    cnt_up(i, X[i])

print(*cnt)

Submission status: Runtime Error

Solution code:
def cnt_up(p, x):
    cnt[p-1] += x
    for i in child[p-1]:
        cnt_up(i, x)


N, Q = map(int, input().split())
child = [[] for _ in range(N)]
cnt = [0] * N
X = [0] * N
for _ in range(N-1):
    a, b = map(int, input().split())
    child[a-1].append(b)

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

for i in range(N):
    cnt_up(i, X[i])

print(*cnt)

Submission status: Runtime Error

Solution code:
def cnt_up(p, x):
    cnt[p-1] += x
    for i in child[p-1]:
        cnt_up(i, x)


N, Q = map(int, input().split())
child = [[] for _ in range(N)]
cnt = [0] * N

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

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

print(*cnt)

Submission status: Runtime Error

Solution code:
def cnt_up(p, x):
    cnt[p-1] += x
    c = child[p-1][:]
    while c:
        cnt_up(c.pop(0), x)


N, Q = map(int, input().split())
child = [[] for _ in range(N)]
cnt = [0] * N

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

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

print(*cnt)

Submission status: Runtime Error

Solution code:
import sys
inputs = sys.stdin.readlines()

n, q = list(map(int, inputs[0].split()))
edges = []
for i in range(n-1):
    edges.append(tuple(map(int, inputs[i+1].split())))
p_x_list = []
for i in range(q):
    p_x_list.append(tuple(map(int, inputs[n+i].split())))

from collections import deque, defaultdict

def dfs_generator(nodes, start):
    nexts = deque([start])
    while nexts:
        node = nexts.popleft()
        nexts.extend(nodes[node]['childs'])
        yield node

nodes = dict({1: dict({'val': 0, 'childs': []})})
for from_, to_ in edges:
    nodes[from_]['childs'].append(to_)
    nodes[to_] = dict({'val': 0, 'childs': []})

part_tree_roots = defaultdict(int)
for p, x in p_x_list:
    part_tree_roots[p] += x

part_tree = defaultdict(list)
for r in part_tree_roots:
    gen = dfs_generator(nodes, r)
    try:
        while True:
            part_tree[r].append(next(gen))
    except StopIteration:
        pass

for n, v in part_tree_roots.items():
    for i in part_tree[n]:
        nodes[i]['val'] += v

for i in range(n-1):
    print(str(nodes[i+1]['val']), end=' ')
print(str(nodes[i+2]['val']))

Submission status: Runtime Error

Solution code:
N, Q = [int(i) for i in input().split(' ')]
tree = {}
for i in range(1, N+1):
  tree[i] = {'children': [], 'num': 0}
  
for _ in range(N-1):
  a, b = [int(i) for i in input().split(' ')]
  tree[a]['children'].append(b)

def send_num(child, num):
  # num += tree[child]['num']
  tree[child]['num'] += num
  for c in tree[child]['children']:
    send_num(c, num)
    
for _ in range(Q):
  a, num = [int(i) for i in input().split(' ')]
  send_num(a, num)

print(*[t['num'] for t in tree.values()])

Submission status: Runtime Error

Solution code:
import sys
inputs = sys.stdin.readlines()

n, q = list(map(int, inputs[0].split()))
edges = []
for i in range(n-1):
    edges.append(tuple(map(int, inputs[i+1].split())))
p_x_list = []
for i in range(q):
    p_x_list.append(tuple(map(int, inputs[n+i].split())))
n, q
edges
p_x_list

from collections import deque, defaultdict

def dfs_generator(nodes, start):
    nexts = deque([start])
    while nexts:
        node = nexts.popleft()
        nexts.extend(nodes[node]['childs'])
        yield node

nodes = dict({1: dict({'val': 0, 'parent': 0, 'childs': []})})
for from_, to_ in edges:
    nodes[from_]['childs'].append(to_)
    nodes[to_] = dict({'val': 0, 'parent': from_, 'childs': []})

part_tree_roots = set([p for p, x in p_x_list])

part_tree = defaultdict(list)
for r in part_tree_roots:
    gen = dfs_generator(nodes, r)
    try:
        while True:
            part_tree[r].append(next(gen))
    except StopIteration:
        pass

for p, x in p_x_list:
    for i in part_tree[p]:
        nodes[i]['val'] += x

for i in range(n-1):
    print(str(nodes[i+1]['val']), end=' ')
print(str(nodes[i+2]['val']))

Submission status: Runtime Error

Solution code:
N, Q = list(map(int, input().split()))
# 双方向に張る
tree = [[] for _ in range(N)]
for i in range(N-1):
    a, b = list(map(int, input().split()))
    a -= 1
    b -= 1
    tree[a].append(b)
    tree[b].append(a)

# queryのスコア表を作る
total = [0 for _ in range(N)]
for i in range(Q):
    p, x = list(map(int, input().split()))
    total[p - 1] += x

# dfs
ans = [0 for _ in range(N)]
def dfs(v, p, value):
    value += total[v]
    ans[v] = value
    for c in tree[v]:
        if c == p: continue
        dfs(c, v, value)

dfs(0, -1, 0)
print(" ".join(list(map(str, ans))))

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
sys.setrecursionlimit(500000)

N,Q = map(int, input().split())
tree = np.eye(N, dtype=int)
AB_list = np.eye(N, dtype=int)
for _ in range(N-1):
    a,b = map(int, input().split())
    a -= 1
    b -= 1
    AB_list[a][b] = 1

break_num = 0
while True:
    tree = np.dot(tree, AB_list)
    break_check = np.count_nonzero(tree)
    if break_check == break_num:
        tree[tree > 0] = 1
        break
    else:
        break_num = break_check

result = np.zeros(N, dtype=int)
for _ in range(Q):
    p,x = map(int, input().split())
    p -= 1
    add_nums = tree[p]
    add_nums[add_nums > 0] = x
    result =  np.add(result, add_nums)
result = " ".join(map(str, result))
print(result)

Submission status: Runtime Error

Solution code:
class Tree:
  treeImpl = {}
  def __init__( self, roots, branches ) :
    for i in range( 1, len( roots ) ) :
      self.treeImpl.setdefault( roots[i], [] ).append( branches[i] )

  def PartialTreeNodes( self, rootNode, ans ):
    if len(ans) == 0 : ans.append( rootNode )
    currentNodes = self.treeImpl.get( rootNode )
    if currentNodes == None: return
    for currentNode in currentNodes:
      ans.append( currentNode )
      self.PartialTreeNodes( currentNode, ans )

# ======================================
n, q = map( int, input().split() )
a = [0]*n
b = [0]*n
p = [0]*q
x = [0]*q

for i in range( 1,n ):
  a[i], b[i] = map( int, input().split() )
  
from collections import defaultdict
scores = defaultdict( int )

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


tree = Tree( a, b )

for i in range( q ): # pで回す
  currentRoot = p[i]
  currentTreeNodes = []
  tree.PartialTreeNodes( currentRoot, currentTreeNodes ) 
  for nodeIndex in currentTreeNodes:
    scores[ nodeIndex ] += x[i]

for value in scores.values():
  print( value, end=" " )

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

add = [0] * n

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

ans = [0] * n

def dfs(v, p, value):
    value += add[v]
    ans[v] = value
    for c in tree[v]:
        if c == p:
            continue
        dfs(c, v, value)

dfs(0, -1, 0)

print(*ans)

Submission status: Runtime Error

Solution code:
def add_and_propagate(tree, x=0):
    tree[1] += x
    for sub in tree[2]:
        add_and_propagate(sub, tree[1])
    
def get_nodes(tree):
    yield tree[:2]
    for sub in tree[2]:
        yield from get_nodes(sub)

def add_children(tree, p, qs, counts):
    def callback(tree):
        tree[2].extend([[q, counts[q-1], []] for q in qs])
    return search(tree, p, callback)

def find_next(p, edges):
    to_remove = set()
    for e in edges:
        if p in e:
            to_remove.add(e)
            yield e[0] if p == e[1] else e[1]
    edges.difference_update(to_remove)

def output(tree):
    print(*(c for n, c in sorted(get_nodes(tree))))

def readlines(N):
    for _ in range(N):
        yield tuple(map(int, input().split()))

N, Q = next(readlines(1))
edges = set(readlines(N - 1))
counts = [0 for _ in range(N)]
for p, x in readlines(Q):
    counts[p-1] += x
tree = [1, counts[0], []]
frontier = [1]
for f in frontier:
    nexts = list(find_next(f, edges))
    frontier.extend(nexts)
    add_children(tree, f, nexts, counts)
add_and_propagate(tree)

output(tree)

Submission status: Runtime Error

Solution code:
from collections import deque


def solve(string):
    n, q, *abpx = map(int, string.split())
    ab, px = abpx[:2 * n - 2], abpx[2 * n - 2:]
    check = [True] * (n + 1)
    t = {i: [] for i in range(n + 1)}
    c = [0] * (n + 1)
    d = deque([1])
    for a, b in zip(*[iter(ab)] * 2):
        t[a].append(b)
        t[b].append(a)
    for p, x in zip(*[iter(px)] * 2):
        c[p] += x
    while len(d) > 0:
        curr = d.pop()
        check[curr] = False
        next_ = [i for i in t[curr] if check[i]]
        for n_ in next_:
            c[n_] += c[curr]
        d.extend(next_)
    return " ".join([str(_c) for _c in c[1:]])


if __name__ == '__main__':
    n, m = map(int, input().split())
    print(solve('{} {}\n'.format(n, m) + '\n'.join([input() for _ in range(n + m)])))

Submission status: Runtime Error

Solution code:
import sys

def main():
    sys.setrecursionlimit(10**6)
    input = sys.stdin.readline
    n, q = map(int, input().split())
    #n, q = map(int, "4 3".split())
    g = [[] for _ in range(n)]
    for i in range(n-1):
        a, b = map(int, input().split())
        #a, b = map(int, ["1 2", "2 3", "2 4"][i].split())
        g[a-1].append(b-1)
        g[b-1].append(a-1)


    add = [0] * n
    for i in range(q):
        p, v = map(int, input().split())
        #p, v = map(int, ["2 10", "1 100", "3 1"][i].split())
        #dfs(p-1, v)
        add[p-1] += v

    ans = [0] * n
    def dfs()
    def dfs(v,p,value): #p: parent of v
        value += add[v]
        ans[v] = value
        for c in g[v]:
            if c == p: continue
            dfs(c,v,value)
    dfs(0, -1, 0)
    """
    def dfs(start, point):
        stack = [start]
        while stack:
            x = stack.pop()
            ans[x] += point
            stack += g[x]
    """

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

if __name__ == '__main__':
    main()

Submission status: Runtime Error

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


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

    ans = [0] * n
    def dfs(start, point):
        stack = [start]
        while stack:
            x = stack.pop()
            ans[x] += point
            stack += g[x]

    for i in range(q):
        p, v = map(int, input().split())
        #p, v = map(int, ["2 10", "1 100", "3 1"][i].split())
        dfs(p-1, v)

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

if __name__ == '__main__':
    main()

Submission status: Runtime Error

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


"""
if __name__ == '__main__':
    main()
"""
n, q = map(int, input().split())
#n, q = map(int, "4 3".split())
g = []
if i in range(n):
    g.append([])
#g = [[] for _ in range(n)]
for i in range(n-1):
    a, b = map(int, input().split())
    #a, b = map(int, ["1 2", "2 3", "2 4"][i].split())
    g[a-1] += append(b-1)

ans = [0] * n
def dfs(start, point):
    stack = [start]
    while stack:
        x = stack.pop()
        ans[x] += point
        stack += g[x]

for i in range(q):
    p, v = map(int, input().split())
    #p, v = map(int, ["2 10", "1 100", "3 1"][i].split())
    dfs(p-1, v)

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

Submission status: Runtime Error

Solution code:

n, q = map(int, input().split())
#n, q = map(int, "4 3".split())

g = [[] for _ in range(n)]

for i in range(n-1):
    a, b = map(int, input().split())
    #a, b = map(int, ["1 2", "2 3", "2 4"][i].split())
    g[a-1] += append(b-1)

ans = [0] * n
def dfs(start, point):
    stack = [start]
    while stack:
        x = stack.pop()
        ans[x] += point
        stack += g[x]

for i in range(q):
    p, v = map(int, input().split())
    #p, v = map(int, ["2 10", "1 100", "3 1"][i].split())
    dfs(p-1, v)

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

Submission status: Runtime Error

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


if __name__ == '__main__':
    main()
"""
n, q = map(int, input().split())
#n, q = map(int, "4 3".split())

g = [[] for _ in range(n)]

for i in range(n-1):
    a, b = map(int, input().split())
    #a, b = map(int, ["1 2", "2 3", "2 4"][i].split())
    g[a-1] += append(b-1)

ans = [0] * n
def dfs(start, point):
    stack = [start]
    while stack:
        x = stack.pop()
        ans[x] += point
        stack += g[x]

for i in range(q):
    p, v = map(int, input().split())
    #p, v = map(int, ["2 10", "1 100", "3 1"][i].split())
    dfs(p-1, v)

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

Submission status: Runtime Error

Solution code:
# https://atcoder.jp/contests/abc138/tasks/abc138_d

from collections import deque

def bfs(graph, start, query):
    queue = deque([])
    acc = query[start] if start in query else 0
    queue.append([start, acc])
    ans = {start:acc}

    while queue:
        idx, acc = queue.popleft()
        for child in graph[idx].keys():
            ans[child] = acc
            if child in query:
                ans[child] += query[child]
            if child in graph:
                queue.append([child, ans[child]])
    [print(ans[i], end=' ') for i in range(1, n+1)]

n,q = map(int, input().split())
tree = {}
start = 1
init = 1
for i in range(n-1):
    a,b = map(int,input().split())
    if a not in tree:
        tree[a] = {}
    tree[a][b] = init
    # if b not in tree:
    #     tree[b] = {}
    # tree[b][a] = init

query = {}
for _ in range(q):
    p, x = map(int,input().split())
    if p not in query:
        query[p] = x
    else:
        query[p] += x
bfs(tree, start, query)

Submission status: Runtime Error

Solution code:
import numpy as np
N,Q = map(int,input().split())
AB = [list(map(int,input().split())) for _ in range(N-1)]
AB.reverse()
T = [[i] for i in range(N+1)]
for a,b in AB:
    T[a]+=T[b]
PQ = [list(map(int,input().split())) for _ in range(Q)]
X = np.array([0]*N)
for p,q in PQ:
    X[T[p]] = X[T[p]] + q
print(*X)

Submission status: Runtime Error

Solution code:
from collections import deque

tree = [[] for i in range(n+1)]
for i in range(n-1):
    a, b = map(int, input().split())
    tree[a].append(b)
    
result = [0]*(n+1)
for i in range(q):
  a, b = map(int, input().split())
  result[a] += b
    
que=deque()
que.append(1)

while que:
  n = que.popleft()
  for i in tree[n]:
    result[i] += result[n]
    que.append(i)
    
for i in result[1:]:
  print(i, 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)]
 
g = [[] for _ in range(N+1)]
for a,b in AB:
    g[a].append(b)
    g[b].append(a)
    
cnt = [0] * (N+1)
for p,x in PX:
    cnt[p] += x

# v: node, p: parent node, add: parent value
def dfs(v, p, add):
    cnt[v] += add
    for nv in g[v]:
        if nv == p:
            continue
        dfs(nv, v, cnt[v])
 
dfs(1, 0, 0)

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

Submission status: Runtime Error

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

def dfs(v, p, add):
    cnt[v] += add
    for nv in g[v]:
        if nv == p:
            continue
        dfs(nv, v, cnt[v])

dfs(1, 0, 0)

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

Submission status: Runtime Error

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

N, Q = map(int, input().split())
AB = [[int(x) for x in input().split()] for _ in range(N-1)]
PX = [[int(x) for x in input().split()] for _ in range(Q)]
 
g = [[] for _ in range(N+1)]
for a,b in AB:
    g[a].append(b)
    g[b].append(a)
 
cnt = [0] * (N+1)
for p,x in PX:
    cnt[p] += x

def dfs(v, p, add):
    cnt[v] += add
    for nv in g[v]:
        if nv == p:
            continue
        dfs(nv, v, cnt[v])

dfs(1, 0, 0)

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

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**5)
n, q = map(int, input().split())

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

ans = [0] * n
pool = {}
def dfs(cur, num):
	ans[cur-1] += num
	if len(stack[cur]) <= 0:
		return 
	for c in stack[cur]:
		dfs(c, num)

for i in range(q):
  p, x = map(int, input().split())
  pool[p] = pool.get(p, 0) + x
for k, v in pool.items():
  dfs(k, v)
print(*ans)

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
AB = [[int(x) for x in input().split()] for _ in range(N-1)]
PX = [[int(x) for x in input().split()] for _ in range(Q)]
 
g = [[] for _ in range(N+1)]
for a,b in AB:
    g[a].append(b)
    g[b].append(a)
    
cnt = [0] * (N+1)
for p,x in PX:
    cnt[p] += x

# v: node, p: parent node, add: parent value
def dfs(v, p, add):
    cnt[v] += add
    for nv in g[v]:
        if nv == p:
            continue
        dfs(nv, v, cnt[v])
 
dfs(1, 0, 0)

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

Submission status: Runtime Error

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

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

ans = [0] * n
pool = {}
def dfs(cur, num):
	ans[cur-1] += num
	if len(stack[cur]) <= 0:
		return
	for c in stack[cur]:
		dfs(c, num)

for i in range(q):
  p, x = map(int, input().split())
  pool[p] = pool.get(p, 0) + x
for k, v in pool.items():
  dfs(k, v)
print(*ans)

Submission status: Runtime Error

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

def dfs(v,p=-1):
    for u in d[v]:
        if (u==p): continue
        w[u]+=w[v];
        dfs(u,v)

d={}
n,q=map(int,input().split())
for i in range(n-1):
    a,b=map(int,input().split())
    if a in d:
        d[a].add(b)
    else:
        d[a]=set([b])
    if b in d:
        d[b].add(a)
    else:
        d[b]=set([a])
w=[0]*(n+1)

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

print(*w[1:])

Submission status: Runtime Error

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

import sys
sys.setrecursionlimit(100000)

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

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

def add_tree(value,tree):
    for i in tree:
        dd_px[i]+=value
        add_tree(dd_px[i],dd_ab[i])
add_tree(dd_px[1],dd_ab[1])
print(*dd_px[1::])

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import sys
input=sys.stdin.readline

def dfs(v,p=-1):
    if v in d:
        for i in d[v]:
            if (i==p): continue
            w[i]+=w[v];
            dfs(i,v)

d={}
n,q=map(int,input().split())
for i in range(n-1):
    a,b=map(int,input().split())
    if a in d:
        d[a].add(b)
    else:
        d[a]=set([b])
    if b in d:
        d[b].add(a)
    else:
        d[b]=set([a])
w=[0]*(n+1)

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

print(*w[1:])

Submission status: Runtime Error

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

tree, add_list = {}, {}

for i in range(1, n+1): tree[i] = []; add_list[i] = 0
point_num = add_list.copy()
for i in p: tree[i[0]].append(i[1])
for i in x: add_list[i[0]] = i[1]

def rec(n, add):
  add += add_list[n]
  point_num[n] += add
  for next_n in tree[n]: rec(next_n, add)

rec(1, 0)

for i in point_num.values():
    print(i, end=" ")

Submission status: Runtime Error

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

score = [0 for _ in range(N)]
 
# 子頂点番号:親頂点番号のdictを生成する
d = {}
for i in range(1,N):
  a,b = map(int,input().split())
  d[b] = a
      
# スコア加算処理
for i in range(1,Q+1):
  p,x = map(int,input().split())
  score[p-1] = x  
for i in range(1,len(score)):
  addScore = score[d[i+1]-1]
  score[i] += addScore
print(*score)

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

stack = [[] for _ in range(n+1)]
stack[0].append(1)
for i in range(n-1):
	stack[AB[i][0]].append(AB[i][1])

ans = [0] * n
pool = {}
def dfs(cur, num):
	ans[cur-1] += num
	if len(stack[cur]) <= 0:
		return
	for c in stack[cur]:
		dfs(c, num)

for px in PX:
	pool[px[0]] = pool.get(px[0], 0) + px[1]
for k, v in pool.items():
  	dfs(k, v)
print(*ans)

Submission status: Runtime Error

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

score = [0 for _ in range(N)]
 
# 子頂点番号:親頂点番号のdictを生成する
d = {}
for i in range(1,N):
  a,b = map(int,input().split())
  d[b] = a
      
# スコア加算処理
for i in range(1,Q+1):
  p,x = map(int,input().split())
  score[p-1] = x
for i in range(1,len(score)):
  addScore = score[d[i+1]-1]
  score[i] += addScore
print(*score)

Submission status: Runtime Error

Solution code:
from collections import defaultdict
n,q=map(int,input().split())
Edges=defaultdict(list)
for _ in range(n-1):
    a,b=map(int,input().split())
    Edges[a-1].append(b-1)
Nodes = [0]*n
for _ in range(q):
    p,x=map(int,input().split())
    Nodes[p-1] += x
 
# A function used by DFS 
def dfs(v,preval,Edges,Nodes,visited): 
    # Mark the current node as visited and print it 
    visited[v]= True
    if v!=0:
        Nodes[v] += preval
    preval = Nodes[v]
 
    # Recur for all the vertices adjacent to this vertex 
    for i in Edges[v]: 
        if visited[i] == False: 
            dfs(i,preval,Edges,Nodes,visited) 
    return Nodes
 
visited = [False]*(len(Nodes)) 
Nodes = dfs(0,Nodes[0],Edges,Nodes,visited) 
 
print(" ".join(list(map(str,Nodes))))

Submission status: Runtime Error

Solution code:
n, q = map(int, input().split())
g = [[] for i in range(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)
print(g)
 
val = [0 for i in range(n)]
score = [0 for i in range(n)]
for i in range(q):
    p,x = map(int, input().split())
    val[p-1] +=x
#print(val)
 
def dfs(p, x):
    if g[p]:
        for c in g[p]:
            score[c]+=x
            dfs(c, x)
for i in range(n):
    dfs(i, val[i])
    score[i] +=val[i]
print(*score)

Submission status: Runtime Error

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

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

def dfs(p, x):
    if g[p]:
        for c in g[p]:
            score[c]+=x
            dfs(c, x)
for i in range(n):
    dfs(i, val[i])
    score[i] +=val[i]
print(*score)

Submission status: Runtime Error

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

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

def dfs(p, x):
    for c in g[p]:
        score[c]+=x
        dfs(c, x)
for i in range(n):
    dfs(i, val[i])
    score[i] +=val[i]
print(*score)

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
connections = [[] for _ in range(N + 1)]
for _ in range(N - 1):
    pa, ki = map(int, input().split())
    connections[pa].append(ki)
    connections[ki].append(pa)
scores = [0 for _ in range(N + 1)]
for _ in range(Q):
    tag, p = map(int, input().split())
    scores[tag] += p

i = 1
fins = []

def dfs(k=1):
    global scores
    global fins
    if k in fins:
        return
    fins.append(k)
    kids = connections[k]
    if not kids:
        return
    for kid in kids:
        if kid in fins:
            continue
        scores[kid]+=scores[k]
        dfs(kid)


dfs()



print(*scores[1:])

Submission status: Runtime Error

Solution code:
import numpy as np
import sys


def dfs(n, prev, count, ans, ind, b, plus):
    count += plus[n]
    ans[n] = count
    for i in range(ind[n], ind[n + 1]):
        if b[i] != prev:
            dfs(b[i], n, count, ans, ind, b, plus)


def preface_px(px, plus):
    for i in range(len(px)):
        plus[px[i, 0] - 1] += px[i, 1]


def preface_ind(a, ind):
    n = -1
    for i in range(len(a)):
        if a[i] > n:
            n = a[i]
            ind[n] = i
    ind[n + 1] = len(a)


def main():
    din = np.fromstring(sys.stdin.buffer.read(), dtype=np.int64, sep=' ')
    N = din[0]
    Q = din[1]
    ab = din[2: 2 * N].reshape(N - 1, 2).T - 1
    ab = np.hstack((ab, ab[[1, 0], :]))
    px = din[2 * N: 2 * N + 2 * Q].reshape(Q, 2)
    arg = np.argsort(ab[0])
    ab = ab[:, arg]

    ind = np.empty(N + 1, dtype=np.int64)
    preface_ind(ab[0], ind)
    plus = np.zeros(N, dtype=np.int64)
    preface_px(px, plus)
    ans = np.zeros(N, dtype=np.int64)
    dfs(0, -1, 0, ans, ind, ab[1], plus)
    print(*ans.tolist())

main()