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:
from collections import defaultdict

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


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


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

Submission status: Runtime Error

Solution code:
n,q = list(map(int,input().split()))
from collections import defaultdict
import sys
sys.setrecursionlimit(100000)

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

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

ret = [0] * (n+1)
def add_tree(node,value):
    retn = value + dd_px[node]
    ret[node] = retn
    for n in dd_ab[node]:
        add_tree(n,retn)
add_tree(1,0)
for i in ret[1::]:
    print(i)

Submission status: Runtime Error

Solution code:
import numpy as np

n,q=map(int,input().split())
a=[[] for i in range(200001)]
flag=[0]*200001
for c in range(n-1):
    d,e=map(int,input().split())
    a[d].append(e)
    flag[d]=1
#print(a)
cnt=np.array([0]*n)

def recsearch(p,x):
    if flag[p]==0:
        cnt[p-1]+=x
        return 0
    for d in range(len(a[p])):
        cnt[a[p][d]-1]+=x
        tmp=a[p][d]
        if flag[tmp]==1:
            recsearch(tmp,x)
        else:
            cnt[tmp]+=x
            return 0
        

for c in range(q):
    p,x=map(int,input().split())
    if p==1:
        cnt+=x
    else:
        if flag[p]==0:
            cnt[p-1]+=x
        else:
            cnt[p-1]+=x
            recsearch(p,x)
            
for c in range(n):
    print(cnt[c],end=" ")
print()

Submission status: Runtime Error

Solution code:
line = input().split()
N = int(line[0])
Q = int(line[1])
g = {}
g2 = {}
for i in range(N-1):
    r = input().split()
    a = int(r[0])
    b = int(r[1])
    if not a in g:
        g[a] = []
    g[a].append(b)
    if not b in g:
        g[b] = []

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

for i in range(Q):
    row = input().split()
    p = int(row[0])
    x = int(row[1])
    suma[p-1] += x

idx = 0
def add(parent):
    chi = g[parent]
    for c in chi:
        suma[c-1] += suma[parent-1] 
        add(c)
add(1)
for i in range(0,N-1):
    print(suma[i], end=' ')
print(suma[N-1])

Submission status: Runtime Error

Solution code:
n, q = int(input().split())
#n = 4
#q = 3

ans = [0]*n
ki = {}
for i in range(1,n+1):
    ki[i] = []

#z = ["1 2", "2 3", "2 4"]

for i in range(n-1):
    e = list(map(int, input().split()))
    #e = list(map(int, z[i].split()))
    ki[e[0]].append(e[1])

#print(ki)

def df(graph, start, point):
    stack = [start]
    visited = []
    while stack:
        v = stack.pop(0)
        ans[v - 1] += point
        if v not in visited:
            visited.append(v)
            stack = graph.get(v, []) + stack

#y = ["2 10", "1 100", "3 1"]
for i in range(q):
    p = list(map(int, input().split()))
    #p = list(map(int, y[i].split()))
    df(ki, p[0], p[1])

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

#v = list(map(int, input().split()))
#n = 3
#v = list(map(int, "500 300 200".split()))
#ans = v[0]
#for i in range(1,n):
#    ans = (v[i] + ans)/2
#print(ans)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
#ABC138D
import sys
sys.setrecursionlimit(100000)

tmp = input().split()
n,q = list(map(lambda a: int(a), tmp))

apex=[]
node=[]

node=[]

for i in range(0,n+1):
	node.append([])
	apex.append(0)

for i in range(1,n):
	tmp = input().split()
	hoge = list(map(lambda a: int(a), tmp))
	node[hoge[0]].append(hoge[1])

for i in range(1,q+1):
	tmp = input().split()
	hoge = list(map(lambda a: int(a), tmp))
	apex[hoge[0]]+=hoge[1]

#print(node)
#print(apex)

def calc(j):
	for i in node[j]:
		apex[i]+=apex[j]
		calc(i)

calc(1)
#print(apex)

ans=str(apex[1])
for i in range(2,n+1):
	ans += " " + str(apex[i])
print(ans)

Submission status: Runtime Error

Solution code:
import sys

input = sys.stdin.readline


class Node:
    def __init__(self, id):
        self.id = id
        self.next = []
        self.val = 0

    def set_node(self, node):
        self.next.append(node)


def add_val(node, val):
    global tree
    node.val += val
    if not node.next:
        return
    for i in node.next:
        add_val(tree[i], val)


n, q = map(int, input().split())
tree = [Node(id) for id in range(n + 1)]

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

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

print(*[tree[i].val for i in range(1, n + 1)])

Submission status: Runtime Error

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

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

matrix = np.zeros((n,n), dtype="int32")

for _ in range(n-1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    matrix[a,b] = 1
    
ans = np.zeros(n, dtype="int32")

for i in range(q):
    p, x = map(int, input().split())
    p -= 1
    queue = [p]
    while True:
        index = queue.pop(0)
        ans[index] += x
        tmp_array = matrix[index, :]
        tmp_index = np.where(tmp_array==1)[0]
        queue.extend(tmp_index)
        if len(queue) == 0:
            break
print(*ans)

Submission status: Runtime Error

Solution code:
from collections import defaultdict


def resolve():
    n, q = map(int, input().split())
    ab = sorted(list(list(map(int, input().split())) for _ in range(n - 1)))
    pq = list(list(map(int, input().split())) for _ in range(q))
    d = defaultdict(list)
    counters = [0] * n
    child_nodes = [[0]] * n
    for a, b in ab:
        d[a].append(b)
    for p, q in pq:
        child = child_nodes[p - 1] if not child_nodes[p - 1] else d[p]
        nodes = [p] + child
        while any([c in d for c in child]):
            new_nodes = []
            for c in child:
                if not child_nodes[c - 1]:
                    new_nodes += child_nodes[c - 1]
                elif c in d:
                    new_nodes += d[c]
            child = new_nodes
            nodes += new_nodes
        child_nodes[p] = nodes
        for n in nodes:
            counters[n - 1] += q
    print(" ".join([str(c) for c in counters]))


if __name__ == "__main__":
    resolve()

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
a = [0] * (N - 1)
b = [0] * (N - 1)
for i in range(N - 1):
    a[i], b[i] = map(int, input().split())

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

parent = [0] * N

#2
for i in range(N):
    parent[i] = [i + 1]

# 1
for i in range(N - 1):
    parent[a[i] - 1].append(b[i])

# 3
for i in range(N):
    for j in range(len(parent[i])):
        for k in range(len(parent[parent[i][j]-1])):
            parent[i].append(parent[parent[i][j]-1][k])
            parent[i] = list(set(parent[i]))

#4
#for i in range(N):
#    parent[i] = list(set(parent[i]))

###########

value = [0] * N

for i in range(Q):
    for j in range(len(parent[p[i]-1])):
        value[parent[p[i]-1][j]-1] += x[i]

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

Submission status: Runtime Error

Solution code:
import numpy as np

n,q = map(int,input().split())
lst = {i+1:[] for i in range(n)}
for _ in range(n-1):
  l,r = map(int,input().split())
  lst[l].append(r)
counter=[0 for _ in range(n)]

for _ in range(q):
  p,x = map(int,input().split())
  temp = [p]
  while len(temp)!=0:
    search_num = temp.pop()
    counter[search_num-1]+=x
    temp+=lst[search_num]
    
ans = ""
for i in counter:
  ans += str(i)+" "
ans.pop()
print(ans)

Submission status: Runtime Error

Solution code:
def add_node(tree, counter, ope, node, value):
    if node in ope:
        value += ope[node]
    counter[node - 1] += value

    if node in tree:
        for i in tree[node]:
            add_node(tree, counter, ope, i, value)


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

tree = {}

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

ope = {}
for j in range(q):
    p, x = map(int, input().split())
    if p not in ope:
        ope[p] = x
    else:
        ope[p] += x

counter = [0] * n

# print(tree, ope)

# for k in ope:
add_node(tree, counter, ope, 1, 0)

print(*counter)

Submission status: Runtime Error

Solution code:
n, q = int(input().split())
#n = 4
#q = 3

ans = [0]*n
ki = {}
for i in range(1,n+1):
    ki[i] = []

z = ["1 2", "2 3", "2 4"]

for i in range(n-1):
    e = list(map(int, input().split()))
    #e = list(map(int, z[i].split()))
    ki[e[0]].append(e[1])

print(ki)

def df(graph, start, point):
    stack = [start]
    visited = []
    while stack:
        v = stack.pop(0)
        ans[v - 1] += point
        if v not in visited:
            visited.append(v)
            stack = graph.get(v, []) + stack

y = ["2 10", "1 100", "3 1"]
for i in range(q):
    p = list(map(int, input().split()))
    #p = list(map(int, y[i].split()))
    df(ki, p[0], p[1])

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

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

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

#c = np.zeros((n+1,n+1))


c = []
for i in range(n+1):
    c.append([i])

for j in reversed(range(n+1)):
    for i in range(n+1):
        if g[i][j] == 1:
            c[i]+=c[j]

#print(c)

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

ans_str = str(ans.astype(int))
ans_str = ans_str.replace('[','').replace(']','')
print(ans_str)

Submission status: Runtime Error

Solution code:

import sys

def get_root_counter(counter, root_num):
    counter += counter_add_dict[root_num]
    if tree_root_dict[root_num] == 0:
        return counter

    return get_root_counter(counter, tree_root_dict[root_num])


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

sys.setrecursionlimit(Q)

C = [0] * (N+1)

tree_root_dict = {}
for i in range(N):
    tree_root_dict[i] = 0

# make tree
for i in range(N-1):
    a, b = map(int, input().split(" "))
    tree_root_dict[b] = a

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

# get counters
for i in range(Q):
    p, x = map(int, input().split(" "))
    counter_add_dict[p] += x

# add counters
for i in range(1, len(tree_root_dict)):
    C[i] = get_root_counter(counter_add_dict[i], tree_root_dict[i])

# print counters
ans = ""
for i in range(1, N+1):
    ans += str(C[i]) + " "

print(ans)

Submission status: Runtime Error

Solution code:
N,Q = map(int,input().split())
Ki_Oya=dict()
Ki_Dict=dict()
Ki_Count=dict()
for i in range(N-1):
  A,B = input().split()
  if A not in Ki_Dict:
    Ki_Dict[A]=set(A)
    Ki_Count[A]=0
    Ki_Oya[A]=set(A)
  if B not in Ki_Dict:
    Ki_Dict[B]=set(B)
    Ki_Count[B]=0
    Ki_Oya[B]=Ki_Oya[A]
  
  Ki_Dict[A].add(B)
  if A in Ki_Oya:
    for j in list(Ki_Oya[A]):
      Ki_Dict[j].add(B)

for i in range(Q):
  P,X = input().split()
  X = int(X)
  for i in list(Ki_Dict[P]):
    Ki_Count[i] += X
Ki_List = list(Ki_Dict.keys())
ans=[]
for i in Ki_List:
  ans.append(str(Ki_Count[i]))
print(" ".join(ans))

Submission status: Runtime Error

Solution code:
N, Q = (int(i) for i in input().split())
a_b = [[int(i) for i in input().split()] for i in range(N - 1)]
p_x = [[int(i) for i in input().split()] for i in range(Q)]

child = {}
parent = {}
node_list = set()
for ab in a_b:
    parent[ab[1]] = ab[0]
    child[ab[0]] = child.get(ab[0], [])
    child[ab[0]].append(ab[1])
    node_list.add(ab[0])
    node_list.add(ab[1])

for k, v in child.items():
    if k != 1:
        child[parent[k]] += v

ans = {}
for px in p_x:
    if px[0] not in node_list:
        continue
    ans[px[0]] = ans.get(px[0], 0) + px[1]
    if px[0] in child.keys():
        for node in child[px[0]]:
            ans[node] = ans.get(node, 0) + px[1]

sorted_nodes = sorted(list(node_list))

for i in sorted_nodes:
    print(ans[i], end=' ')

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
d = dict()
ans = [0] * N
for i in range(N-1):
    a, b = map(int, input().split())
    d.setdefault(a, []).append(b)
for i in range(Q):
    p, x = map(int, input().split())
    ans[p-1] += x
    for v in d.values():
        for vv in v:
            ans[vv] += x
print(' '.join(ans))