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 numpy as np
n,q=list(map(int, input().split()))
result = {i+1:0 for i in range(n)}
ar = np.eye(n)

for i in range(n-1):
    a,b = list(map(int, input().split()))
    ar[0:a,a-1:b] += 1
for i in range(q):
    a,b = list(map(int, input().split()))
    m = ar[a-1]
    for j in range(len(m)):
        if m[j] != 0:
            result[j+1] += b
        else:
            result[j+1] += 0
r = list(result.values())
res = map(str, r)
print(' '.join(res))

Submission status: Runtime Error

Solution code:
def bfs(s):
  global adj,n
  queue = [s]
  visited = [False]*(n+1)
  res = []
  while len(queue)!=0:
    f = queue[0]
    res.append(f)
    queue.remove(f)
    for n in adj[f]:
      if not visited[n]:
        visited[n] = True
        queue.append(n)
  return res
n,q = [int(x) for x in input().split()]
adj = dict()
reachable_vertices = dict()
counter = [0]*(n+1)
for i in range(1,n+1):
  adj[i] = []
for i in range(1,n):
  u,v = [int(x) for x in input().split()]
  adj[u].append(v)
for _ in range(q):
  p,x = [int(x) for x in input().split()]
  if p not in reachable_vertices:
    reachable_vertices[p] = bfs(p)
  for node in reachable_vertices[p]:
    counter[node]+=x
for i in range(1,n+1):
  print(counter[i],end=' ')

Submission status: Runtime Error

Solution code:
N,Q= map(int, input().split())
es=[]
ope=[]
point=[0]*N
for _ in range(N-1):
    a,b=map(int, input().split())
    es.append((a,b))
for _ in range(Q):
    p,x=map(int, input().split())
    ope.append((p,x))
import numpy as np
point=np.array(point)
nodes=np.eye(N, dtype=int)
for e in es:
    nodes[e[0]-1][e[1]-1]=1
    nodes[:,e[1]-1]=np.logical_or(nodes[:,e[1]-1],nodes[:,e[0]-1])
for o in ope:
    point+=nodes[o[0]-1]*o[1]
string=""
for i in range(N):
    string+=str(int(point[i]))+" "
print(string)

Submission status: Runtime Error

Solution code:


MAX = 100002

def add_num(nn, x):
    if nn == -1:
        return
    Tree[nn][0] += x
    for ni in Tree[nn][1]:
        add_num(ni, x)


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



Tree = []
for m in range(MAX-1):
    Tree.append([-1, [-1]])

nodes = set()
nodes.add(1)

for i in range(N-1):
    ipti = input().split()
    a = int(ipti[0])
    b = int(ipti[1])

    Tree[a][0] = 0
    Tree[a][1].insert(0, b)
    Tree[b][0] = 0

    nodes.add(b)



for i in range(Q):
    ipti = input().split()
    p = int(ipti[0])
    x = int(ipti[1])

    cands = set()

    Tree[p][0] += x

    for pi in range(p,MAX-1):
        if Tree[pi] == -1:
            break
        for pii in Tree[pi][1]:
            cands.add(pii)
    for ci in cands:
        Tree[ci][0] += x

    #add_num(p, x)


for n in nodes:
    print(Tree[n][0])

Submission status: Runtime Error

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

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

class Node():
    def __init__(self):
        self.children = []
        self.count = 0

def add_count(G, v=0):
    for child in G[v].children:
        G[child].count += G[v].count
        add_count(G, child)

G = [Node() for _ in range(N)]
for _ in range(N-1):
    p, c = map(int, input().split())
    p -= 1
    c -= 1
    G[p].children.append(c)

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

add_count(G)



counts = [node.count for node in G]
print(*counts)

Submission status: Runtime Error

Solution code:
import sys
input=sys.stdin.readline
N,Q=map(int,input().split())
dg={i:[[],0] for i in range(1,N+1)}
for i in range(1,N):
    a,b=map(int,input().split())
    dg[a][0].append(b)
    dg[b][0].append(a)
#print(dg)
def habatan(p,me):
    if me!=1:
        dg[me][0].remove(p)
    for c in dg[me][0]:
        habatan(me,c)

habatan(0,1)#dg親消し
#print(dg)
#dv={i:0 for i in range(1,N+1)}
for i in range(Q):
    p,x=map(int,input().split())
    #dv[p]+=x
    dg[p][1]+=x
#dans={}
def habatan1(p,me):
    if me!=1:
        #dv[me]+=
        dg[me][1]+=dg[p][1]
    #for c in dg[me]:
    for c in dg[me][0]:
        habatan1(me,c)
habatan1(0,1)
for i in range(1,N+1):
    #print(dv[i],end=" ")
    print(dg[i][1],end=" ")
print("")

Submission status: Runtime Error

Solution code:
def addtree(T,TN,x):
  if len(T[TN])==1:
    T[TN][0]+=x   
    return
  else:
    for i in range(1,len(T[TN])):
      addtree(T,T[TN][i],x)
    T[TN][0]+=x   
    return
  

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

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

for i in range(Q):
  p,x=map(int,input().split())
  addtree(T,p,x)

for i in range(N):
  print(T[i+1][0],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())
    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:
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 = 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:
def bubunki(akan):
    for l in range(n-1) :
        if(a[l] == akan) :
            z[b[l]] += x[k]
            bubunki(b[l]) 
    return 



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

a = []
b = []
p = [] 
x = []
z = [0] * (n+1)

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

for j in range(q) :
    p1,x1 = map(int,input().split())
    # p.append(p1)
    # x.append(x1)
    z[p[k]] += x1
    bubunki(p1)        


# for k in range(q) :

    # z[p[k]] += x[k]

    # bubunki(p[k])        

s = ""
for l in range(1,n+1) :
    s +=  str(z[l]) + " "
    
print(s)

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] = [b]
    else:
        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:
# -*- coding: utf-8 -*-

import sys

debug = False

def log(text):
    if debug:
        print(text)

def parse_input(lines_as_string = None):

    global debug
    lines = []
    if lines_as_string is None:
        debug = False
        lines.append(input())
        tokens = lines[0].split(" ")
        n = int(tokens[0])
        q = int(tokens[1])
        for i in range(n-1+q):
            lines.append(input())
    else:
        debug = True
        lines = [e for e in lines_as_string.split("\n")][1:-1]
        tokens = lines[0].split(" ")
        n = int(tokens[0])
        q = int(tokens[1])        

    if debug:
        log("lines=%s" % lines)

    ab = []
    for i in range(1, n):
        ab.append([int(e) for e in lines[i].split(" ")])

    px = []
    for i in range(n, n+q):
        px.append([int(e) for e in lines[i].split(" ")])

    parsed = (n, q, ab, px)

    if debug:
        log("parsed=(%s, %s, %s, %s)" % (n, q, ab, px))

    return parsed


def solve(n, q, ab, px):


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


    counter = []
    for i in range(n):
        counter.append(0)

    def add_value_to_child(p, x):
        if debug:
            log("counter=%s" % counter)
            log("p=%s" % p)
            log("x=%s" % x)
            log("tree[%d]=%s" % (p, tree[p]))

        counter[p] = counter[p] + x
        if not tree[p]:
            return
        else:
            for c in tree[p]:
                if debug:
                    log("c=%s, x=%s" % (c, x))
                add_value_to_child(c, x)

    for p, x in px:
        if debug:
            log("p=%s, x=%s" % (p, x))
        add_value_to_child(p-1, x)

    result = [e for e in counter]

    return result


def main():
    # 出力
    result = solve(*parse_input())
    if isinstance(result, list):
        for r in result:
            print("%s" % r)
    else:
        print("%s" % result)


if __name__ == '__main__':

    main()

Submission status: Runtime Error

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

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

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

children = defaultdict(set)
for i in range(1,N+1):
    children[i].add(i)
    d = deque(connection[i])
    checked = set(connection[i])
    while len(d) > 0:
        x = d.popleft()
        children[i].add(x)
        d += connection[x]

ans = []
for i in range(1, N+1):
    for v in children[i]:
        cnt += operations[v]
        print(cnt)
    ans.append(str(cnt))
print(' '.join(ans))

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):
#     ans.append(node.point)
#     for child in node.child:
#         printNode(child)

def printNode(node):
    for i in range(1, n+1):
        ans.append(nodes[i].point)

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

def traverse(node, point):
#    print(node.point)
    node.point += point
    for child in node.child:
        traverse(child, node.point)

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

traverse(nodes[1], 0)
printNode(nodes[1])

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

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

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
sys.setrecursionlimit(10000)

N,Q=map(int,input().split())
graph=[[] for _ in range(N+1)]
for _ in range(N-1):
    a,b=map(int,input().split())
    graph[a].append(b)
counter=[0 for _ in range(N+1)]
for _ in range(Q):
    p,x=map(int,input().split())
    counter[p]+=x

def dfs(G,v):
    seen[v]=True
    for next_v in G[v]:
        if G[next_v]==True:
            continue
        else:
            counter[next_v]+=counter[v]
            dfs(G,next_v)

seen=[False for _ in range(N+1)]
dfs(graph,1)
ans=''
for i in range(N):
    ans+=str(counter[i+1])+' '
print(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:
    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:
#-------------------------------------------------------------------
import sys
def p(*_a):
  _s=" ".join(map(str,_a))
  #print(_s)
  sys.stderr.write(_s+"\n")
#-------------------------------------------------------------------
N, A = map(int, input().split())		# 5 7 2

M = [ [] for _ in range(N+1) ]	#=> [[], [], [], [], [], [], [], []]
for i in range(N-1):
	a, b = map(int, input().split())		# 5 7 2
	M[a].append(b)

P=[0]*(N+1)
for i in range(A):
	a, x = map(int, input().split())		# 5 7 2
	P[a]+=x


M[0]=[1]
B=[0]*(N+1)

def aaa(i):
	L=sorted(M[i])
	for l in L:
		B[l]+=P[l]+B[i]
		aaa(l)

aaa(0)

p("M ",M)
p("P ",P)
p("B ",B)


print( *B[1:] )

Submission status: Runtime Error

Solution code:
import sys

input = sys.stdin.readline


class Node:
    def __init__(self, id):
        self.id = id
        self.node1 = 0
        self.node2 = 0
        self.val = 0

    def set_node(self, node):
        if self.node1 == 0:
            self.node1 = node
        else:
            self.node2 = node


def add_val(node, val):
    global tree
    if node.id == 0:
        return
    node.val += val
    add_val(tree[node.node1], val)
    add_val(tree[node.node2], 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:
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])

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

###########33

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:


MAX = 100002

def add_num(nn, x):
    if nn == -1:
        return
    Tree[nn][0] += x
    for ni in Tree[nn][1]:
        add_num(ni, x)


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



Tree = []
for m in range(MAX):
    Tree.append([-1, [-1]])

nodes = set()
nodes.add(1)

for i in range(N-1):
    ipti = input().split()
    a = int(ipti[0])
    b = int(ipti[1])

    Tree[a][0] = 0
    Tree[a][1].insert(0, b)
    Tree[b][0] = 0

    nodes.add(b)



for i in range(Q):
    ipti = input().split()
    p = int(ipti[0])
    x = int(ipti[1])

    cands = set()

    Tree[p][0] += x

    for pi in range(p,MAX):
        if Tree[pi] == -1:
            break
        for pii in Tree[pi][1]:
            cands.add(pii)
    for ci in cands:
        Tree[ci][0] += x

    #add_num(p, x)


for n in nodes:
    print(Tree[n][0])

Submission status: Runtime Error

Solution code:
n,q = map(int,input().split())
l = [ [] for i in range(n)]
for _ in range(n-1):
    a,b = map(int,input().split())
    l[a-1].append(b-1)
ans = [0 for _ in range(n)]
p = [list(map(int,input().split())) for i in range(q)]
def f(p,x):
    ans[p] +=x
    for i in l[p]:
        f(i,x)
for p1 in p:
    f(p1[0]-1,p1[1])
print((ans))

Submission status: Runtime Error

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

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

    if a not in tree_dict:
        tree_dict[a] = [b]
    else:
        tree_dict[a].append(b)

#value_dict = {k:0 for k in list(set(ab_list))}                                          
value_list = list(set(ab_list))

px_dict = {}
for i in range(Q):
    p, x = map(int, input().split())
    if p in px_dict:
        px_dict[p] += x
    else:
        px_dict[p] = x

out = ""
for v in value_list:
    x = px_dict[v]
    if v in tree_dict:
        tree_list = tree_dict[v]
        for t in tree_list:
            if t in px_dict:
                px_dict[t] += x
            else:
                px_dict[t] = x
    if v in px_dict:
        o = str(px_dict[v])
    else:
        o = str(0)
    out += o + " "

print(out)

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

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 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:
N, Q = map(int, input().split())
nodes = set()
stree = {}
for n in range(N-1):
    a, b = map(int, input().split())
    nodes.add(a)
    if stree.get(a) is None:
        stree[a] = set()
    stree[a].add(b)

memo = {}
def fla(p):
    if memo.get(p) is not None:
        return memo[p]
    cs = stree.get(p)
    if cs is None:
        return None
    subs = set(cs)
    for c in cs:
        memo[c] = fla(c)
        if memo[c]:
            subs |= memo[c]
    memo[p] = subs
    return subs

x = [0]*N
for q in range(Q):
    node, add = map(int,input().split())
    x[node-1] += add
    if fla(node) is not None:
        for c in fla(node):
            x[c-1] += add
#print(memo)
print(' '.join(map(str, x)))

Submission status: Runtime Error

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

# 各ノードのリンクを記録
link_list = [[] for i in range(n-1)]
for i in range(n-1):
  a, b = map(int, input().split())
  link_list[a - 1].append(b)
  
# 各ノードの部分木の全てのノードをリストアップ
link_list2 = [[] for i in range(n-1)]
for i in range(n-1, 0, -1):
  link_list2[i - 1] += link_list[i - 1]
  if i < n-1:
    for j in link_list[i - 1]:
      if j < n - 1:
        link_list2[i - 1] += link_list2[j - 1]
link_set = [set(link) for link in link_list2]

# カウンターの計算を実施
counters = [0] * n
for i in range(q):
  p, x = map(int, input().split())
  counters[p - 1] += x
  for node in link_set[p - 1]:
    counters[node - 1] += x
str_counters = [str(c) for c in counters]
print(' '.join(str_counters))

Submission status: Runtime Error

Solution code:
class Node:
    def __init__(self, id):
        self.id = id
        self.node1 = 0
        self.node2 = 0
        self.val = 0

    def set_node(self, node):
        if self.node1 == 0:
            self.node1 = node
        else:
            self.node2 = node


def add_val(node, val):
    global tree
    if node.id == 0:
        return
    node.val += val
    add_val(tree[node.node1], val)
    add_val(tree[node.node2], 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:


n,q = (int(num) for num in input().split())
neighbor = [[] for _ in range(n)]
visited = [0] * n
val = [0] * n
ab = []
for i in range(n-1):
    a,b = (int(num)-1 for num in input().split())
    ab.append((a,b))

    
for item in ab:
    a = item[0]
    b = item[1]
    neighbor[a].append(b)
    neighbor[b].append(a)
    
        
#print(par)
#print(neighbor)
#print(rank)

for _ in range(q):
    p,x = (int(num) for num in input().split())
    p -= 1
    val[p] += x
    
def calc(idx,neighbor,val,bias):
    val[idx] += bias
    for i in neighbor[idx]:
        if visited[i] == 0:
            visited[i] = 1
            calc(i,neighbor,val,val[idx])

visited[0] = 1
calc(0,neighbor,val,0)    
ans = ""    
for num in val:
    ans += str(num) + " "
print(ans)

Submission status: Runtime Error

Solution code:
n,q = list(map(int,input().split()))
from collections import defaultdict
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
    if dd_px[node]:
        retn += dd_px.pop(node)
    ret[node] += retn
    if dd_ab[node]:
        for n in dd_ab.pop(node):
            add_tree(n,retn)
add_tree(1,0)
for i in ret[1::]:
    print(i)

Submission status: Runtime Error

Solution code:
N, Q = map(int, input().split())
vec = [ [] for _ in range(N)]
for _ in range(N-1) :
    u, v = map(int, input().split())
    vec[u-1].append(v-1)
com = []
for _ in range(Q) :
    p, x = map(int, input().split())
    com.append([p-1,x])
#print(vec)
#print(com)
num = [0] * N
#print(num)
links= []

def update(vec,t,a):
  a.extend(vec[t])
  v = vec[t]
  for i in v:
    a = update(vec,i,a)
  return a

for i in range(N):
  a = []
  s = update(vec,i,a)
  links.append(s)
#print(links)

for t in range(len(com)):
  p,x = com[t]
  num[p] += x
  su = links[p]
  for i in su:
    #print(i)
    num[i] += x
  
for i in range(len(num)):
  print(num[i],"",end = "")

Submission status: Runtime Error

Solution code:
import numpy as np
N,Q = map(int,input().split())
ans = np.array([0]*N)
test = np.array([1]*N)
test = np.diag(test)
p = []
x = []
for i in range(1,N):
    ai,bi = map(int,input().split())
    test[ai-1,bi-1]+=1
for j in range(Q):
    pj,xj = map(int,input().split())
    p.append(pj)
    x.append(xj)

for k in reversed(range(N)):
    check = np.where(test[k] > 0)
    test[k]+=np.sum(test[check],axis=0)
test = np.where(test > 0,1,0)
for j in range(Q):
    ans += test[p[j]-1]*x[j]
    
print(' '.join(map(str,ans)))

Submission status: Runtime Error

Solution code:

def count_add(info_dic, pi_xi_sum_lst, current_node, adding):
    info_dic[current_node][0] += adding
    for i in info_dic[current_node][1]:   #先の枝についても再帰
        adding += pi_xi_sum_lst[i]
        count_add(info_dic, pi_xi_sum_lst, i, adding)
        adding -= pi_xi_sum_lst[i]

def glaph_2_tree(info_dic, passed_place, current_node):
    next_nodes_lst = info_dic[current_node][1][:]
    for next_node in next_nodes_lst:
        if passed_place[next_node]: # 通ったことがあったら、
            info_dic[current_node][1].remove(next_node)
        else:
            passed_place[next_node] = True
            glaph_2_tree(info_dic, passed_place, next_node)
            passed_place[next_node] = False
    passed_place[next_node] = True

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

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

for _ in range(N-1): # 10**5
    ai, bi = map(int, input().split())
    info_dic[ai][1].append(bi)
    info_dic[bi][1].append(ai)

passed_place = [False] * (N+1)
passed_place[1] = True
glaph_2_tree(info_dic, passed_place, 1) # 10**5
#print() ##################
pi_xi_sum_lst = [0]*(N+1)
for _ in range(Q): # 10**5
    pi, xi = map(int, input().split())
    pi_xi_sum_lst[pi] += xi

count_add(info_dic, pi_xi_sum_lst, current_node=1, adding=pi_xi_sum_lst[1])

output_str = ""
for i in range(1, N+1):
    output_str += str(info_dic[i][0]) + " "

print(output_str)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
# 整数の入力
# from functools import reduce
from collections import defaultdict


def main():
    # n, q
    n, q = map(int, input().split())

    # a, b
    a = []
    b = []
    for _ in range(0, n - 1):
        ai, bi = map(int, input().split())
        a.append(ai)
        b.append(bi)

    # p, x
    p = []
    x = []
    for _ in range(0, q):
        pi, xi = map(int, input().split())
        p.append(pi)
        x.append(xi)

    print(process(n, q, a, b, p, x))


def process(n, q, a, b, p, x):
    points = defaultdict(int)
    graph = defaultdict(list)
    for i in range(0, n - 1):
        graph[a[i]].append(b[i])

    for i in range(0, q):
        target = p[i]
        xi = x[i]
        subtree(points, target, graph, xi)

    points_sorted = map(lambda x: str(x[1]), sorted(
        points.items(), key=lambda x: x[0]))
    return ' '.join(points_sorted)


def subtree(points, target, graph, x):
    points[target] += x
    for i in graph[target]:
        subtree(points, i, graph, x)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
n, q = map(int, input().split())
E = [[] for _ in range(n)]
for _ in range(n-1):
    a, b = map(int, input().split())
    E[a-1].append(b-1)
P = [0] * n
for _ in range(q):
    p, x = map(int, input().split())
    P[p-1] += x
result = [0] * n
def r(current, point):
    result[current] += point
    for ee in E[current]:
        r(ee, point+P[ee]) 
 
r(0, P[0])

print(*result)

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)

dv = {}
for i in range(q):
    sta,val = map(int,input().split())
    if sta not in dv:
        dv[sta] = val 
    else:
        dv[sta]+=val
    

#print(d)
#print(dv)  

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

ans = cal_(ans,1,0)

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

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

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

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

Submission status: Runtime Error

Solution code:
NQ = map(int,raw_input().split())
n = NQ[0]
q = NQ[1]

def update(node,p,x):
    node[p][1] += x
    for i in range(p+1,n):
        if node[i][0] == p:
            update(node,i,x)


node = [[0,0] for _ in range(n)]

for _ in range(n-1):
    ab = map(int,raw_input().split())
    node[ab[1]-1][0] = ab[0]-1

for _ in range(q):
    px = map(int,raw_input().split())
    p = px[0]-1
    x = px[1]
    update(node,p,x)

for r in node: print r[1],

Submission status: Runtime Error

Solution code:
import numpy as np
N, Q = map(int, raw_input().split())

w = np.zeros((N, N))
c = np.zeros((N, 1))

def plus(w, p, x, c, N):
  cl = c
  cl[p-1]+=x
  for i in range(p - 1, N):
    for j in range(N):
      if(w[i, j]) == 1:
        cl[j] += x
  return cl

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

for j in range(Q):
  p, x = map(int, raw_input().split())
  c = plus(w, p, x, c, N)

out = ""
for i in range(N):
  out += "{}".format(int(c[i,0])) + " "
print out