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 = map(int, input().split())
tree = np.eye(N, dtype=int)
branch = np.zeros((N, N), dtype=int)
for _ in range(N-1):
    a,b = map(int, input().split())
    a -= 1
    b -= 1
    for i in range(N):
        branch[a][b] = 1

break_num = 0
while True:
    tree = tree + np.dot(tree, branch)
    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
    result += tree[p] * x
result = " ".join(map(str, result))
print(result)

Submission status: Runtime Error

Solution code:
import numpy as np
N,Q = map(int, input().split())
tree = np.eye(N, dtype=int)
branch = np.zeros((N, N), dtype=int)
for _ in range(N-1):
    a,b = map(int, input().split())
    a -= 1
    b -= 1
    for i in range(N):
        branch[a][b] = 1

break_num = 0
while True:
    tree = tree + np.dot(tree, branch)
    print(tree)
    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
    result += tree[p] * x
result = " ".join(map(str, result))
print(result)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.input
n,q = map(int,input().split())
tree = [[] for i 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)

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

#入力

def dfs(pre,now,w):
    ans[now] += w
    for i in tree[now]:
        if i != pre:
            dfs(now,i,ans[now])

dfs(-1,0,0)

print(*ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10000)

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

res = [0]*(n+1)
def add_x(p, x):
    res[p] += x
    for child in tree[p]:
        new_x = x+adds[child]
        add_x(child, new_x)

add_x(1, adds[1])

print(*res[1:])

Submission status: Runtime Error

Solution code:
from sys import setrecursionlimit
setrecursionlimit(10000000)
n, q = map(int, input().split())

ct = [0] * (n+1)
o = [0] * (n+1)
g = [[] for _ in range(n+1)]

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

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

def dfs(p, parent):
  ct[p] += o[p] + ct[parent]
  for i in g[p]:
    if i != parent:
      dfs(i, p)
dfs(1, 0)
print(*counter[1:])

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
#sys.setrecursionlimit(100000)
N,Q = map(int,input().split())
to = [[] for _ in range(N+1)]
ans = [0 for _ in range(N+1)]

for _ in range(N-1):
    a,b=map(int,input().split())
    to[a].append(b)
    to[b].append(a)
for _ in range(Q):
    px = list(map(int,input().split()))
    ans[px[0]] += px[1]

def dfs(v, p):
    for u in to[v]:
        if u == p:
            continue
        ans[u] += ans[v]
        dfs(u, v)
dfs(1, -1)
print(*ans[1:])

Submission status: Runtime Error

Solution code:
import numpy as np
N,Q = map(int, input().split())
tree = np.eye(N, dtype=int)
branch = np.zeros((N, N), dtype=int)
for _ in range(N-1):
    a,b = map(int, input().split())
    a -= 1
    b -= 1
    for i in range(N):
        if tree[i][a] == 1:
            tree[i][b] = 1
result = np.zeros(N, dtype=int)
for _ in range(Q):
    p,x = map(int, input().split())
    p -= 1
    result += tree[p] * x
result = " ".join(map(str, result))
print(result)

Submission status: Runtime Error

Solution code:

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

to = [[] for i in range(n)]


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

score = [0]*n

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


def down_tree(index, parent=-1):
    global score
    for i in to[index]:
        if i == parent:
            continue
        score[i] += score[index]
        down_tree(i, index)
    return


down_tree(0)

for i in range(len(score)):
	print(score[i])

Submission status: Runtime Error

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

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

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

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

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:

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

to = [[] for i in range(n)]


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

score = [0]*n

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


def down_tree(index, parent=-1):
    global score
    for i in to[index]:
        if i == parent:
            continue
        score[i] += score[index]
        down_tree(i, index)
    return


down_tree(0)

print(*score)

Submission status: Runtime Error

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

res = [0]*(n+1)
def add_x(p, x):
    res[p] += x
    for child in tree[p]:
        new_x = x+adds[child]
        add_x(child, new_x)

add_x(1, adds[1])

print(*res[1:])

Submission status: Runtime Error

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

import sys
import collections

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

counter = [0 for _ in range(n+1)]
o = collections.defaultdict(int)
g = collections.defaultdict(list)

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

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


def dfs(p, parent):
  counter[p] += o[p]
  for i in g[p]:
    if i == parent:
      counter[p] += counter[i]
    else:
      dfs(i, p)
 
dfs(1, 0)
print(*counter[1:])

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
#include <tuple>
using namespace std;

int main() {

    int N, Q;
    cin >> N >> Q;
    vector<int> nodes(N, 0);
    int a, b, p, x;
    vector<tuple<int, int>> connections;
    for(int i=0;i<N-1;i++){
        cin >> a >> b;
        connections.emplace_back(make_tuple(a, b));
    }
    for(int i=0;i<Q;i++){
        cin >> p >> x;
        nodes.at(p-1) += x;
    }
    sort(connections.begin(), connections.end());
    tuple<int, int > tup1;
    for(int i=0;i<N-1;i++){
        tup1 = connections.at(i);
        nodes.at(get<1>(tup1)-1) += nodes.at(get<0>(tup1)-1);
    }
    for (int i=0;i<N;i++){
        cout << nodes.at(i);
        if(i==N-1){
            cout << endl;
        } else {
            cout << " ";
        }
    }
}

Submission status: Runtime Error

Solution code:
#abc138d

n,q=map(int,raw_input().split())
f=[0]*200000
g=[0]*200000
for i in xrange(1,n):
 a,b=map(int,raw_input().split())
 f[b]=a
for i in xrange(1,q+1):
 p,x=map(int,raw_input().split())
 g[p]+=x
for i in xrange(1,n+1):
 g[i]+=g[f[i]]
 print g[i],
print

Submission status: Runtime Error

Solution code:
#abc138d

n,q=map(int,raw_input().split())
f=[0]*200000
g=[0]*200000
for i in xrange(1,n):
 a,b=map(int,raw_input().split())
 f[b]=a
for i in xrange(1,q+1):
 a,x=map(int,raw_input().split())
 g[a]+=x
for i in xrange(1,n+1):
 g[i]+=g[f[i]]
 print g[i],
print

Submission status: Runtime Error

Solution code:
from collections import defaultdict, deque
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)
    connection[b].append(a)

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


ans = defaultdict(int)

def func(node,p_node):
    ans[node] += operations[node]
    if p_node != 0:
        connection[node].remove(p_node)
    for c_node in connection[node]:
        ans[c_node] += ans[node]
        func(c_node, node)

func(1, 0)

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

Submission status: Runtime Error

Solution code:
import networkx as nx
g = nx.DiGraph()

N, Q = map(int, input().split())
for i in range(N-1):
    g.add_path(input().split())

counter = {}
for n in g.nodes():
    counter[n] = 0

for i in range(Q):
    p, x = input().split()
    counter[p] += int(x)
    for d in nx.descendants(g,p):
        counter[d] += int(x)

for c in counter.keys():
    if not counter[c] == 0:
        print(counter[c], end=' ')
print()

Submission status: Runtime Error

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

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

def dfs2(i, parent):
    for j in trees[i]:
        if j == parent: continue
        values[j] += values[i]
        dfs2(j, i)

dfs2(0, -1)
print(*values)

Submission status: Runtime Error

Solution code:
import sys
 sys.setrecursionlimit(10**9)
 
def dfs(now, prev):
    ans[now]+=(h[now]+ans[prev])
    # 今いる頂点から行ける頂点を順に next に入れてループ
    for next in g[now]:
        if next != prev:
            if memo[next]==True:
                # 過去に訪れていれば終わらせる
                return False
            else:
                memo[next] = True
                dfs(next, now)
 
#木構造の取り込み 
n, q = map(int, input().split())
g = [[] * n for i in range(n)]
for i in range(n-1):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    g[u].append(v)
    g[v].append(u)

#操作の取り込み
h=[0]*n
for i in range(q):
    u, v = map(int, input().split())
    u -= 1
    h[u]+=v

#初期のカウンター
ans=[0]*n
memo = [False for i in range(n)]

#DFSでカウンターを動かす
dfs(0,0)
 
print(' '.join(map(str, ans)))

Submission status: Runtime Error

Solution code:
import pprint
import sys
sys.setrecursionlimit(10000)

def comp(s, l):
    ans = set(s)
    l2 = s
    for i in l2:
        if i != 0:
            ans = ans | comp(l[i], l)
    return ans


def solve():
    n, q = map(int, input().split())
    l = [[0] for i in range(n+1)]
    ans = [0]*(n+1)
    for i in range(n-1):
        a, b = map(int, input().split())
        l[a].append(b)
    for i in range(q):
        num, point = map(int, input().split())
        li = list(comp(l[num], l))
        li.append(num)
        li = list(set(li))
        for j in li:
            ans[j] += point
    ans2 = list(map(str, ans))
    ans3 = ' '.join(ans2[1::])
    print(ans3)


if __name__=="__main__":
    solve()

Submission status: Runtime Error

Solution code:
import pprint
import sys
sys.setrecursionlimit(10000)

def comp2(num, ll, sl, check):
    if check[num] == 1:
        return sl
    else:
        check[num] = 1
        sl[num].add(num)
        for i in ll[num]:
            sl[num] = sl[num] | (comp2(i, ll, sl, check))[i]
            '''print("num ", num, " i ", i)
            print("sl ", sl)'''
        return sl


def solve():
    n, q = map(int, input().split())
    l = [[0] for i in range(n+1)]
    check = [0 for i in range(n+1)]
    group = [set() for i in range(n+1)]
    ans = [0]*(n+1)
    points = [0 for i in range(n+1)]
    check[0] = 1
    for i in range(n-1):
        a, b = map(int, input().split())
        l[a].append(b)
    for i in range(1,n+1):
        group = comp2(i,l,group,check)
    for i in range(q):
        num, point = map(int, input().split())
        points[num] += point
    for i in range(1,n+1):
        li = list(group[num])
        for j in li:
            ans[j] += points[i]
    ans2 = list(map(str, ans))
    ans3 = ' '.join(ans2[1::])
    print(ans3)


if __name__=="__main__":
    solve()

Submission status: Runtime Error

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

nodes = [[] for _ in range(N)]
values = [0 for _ in range(N)]

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

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

def dfs(i, p):
  for c in nodes[i]:
    if c != p:
      values[c] += values[i]
      dfs(c, i)

dfs(0, None)
print(*values)

Submission status: Runtime Error

Solution code:
class TreeNode:
    def __init__(self):
        self.val = 0
        self.vertex = []


def make_trees(n, A, B):
    trees = []
    for i in range(n):
        trees.append(TreeNode())
    for i in range(len(A)):
        a = A[i]-1
        b = B[i]-1
        trees[a].vertex.append(b)
    return trees

def dfs(node: TreeNode, carry: int, trees):
    if node:
        node.val += carry
        for i in node.vertex:
            dfs(trees[i], node.val, trees)

def sol(n, q, A, B, P, X):
    trees = make_trees(n, A, B)
    for i in range(len(P)):
        p = P[i]-1
        x = X[i]
        t = trees[p]
        # dfs, give point x
        t.val += x
    # accmulative run
    dfs(trees[0], 0, trees)
    #
    return " ".join([str(t.val) for t in trees])
    #return n, q, A, B, P, X



do_submit = True
#do_submit = False

def input_parse(input_str):
    lines = [x.strip() for x in input_str.split("\n") if x.strip()]
    parsed_lines = [list(map(str, line.split())) for line in lines]
    print(parsed_lines)
    n = int(parsed_lines[0][0])
    q = int(parsed_lines[0][1])
    A = []
    B = []
    P = []
    X = []
    for i in range(1, n-1+1):
        a = int(parsed_lines[i][0])
        b = int(parsed_lines[i][1])
        A.append(a)
        B.append(b)
    for i in range(n, 1+n+q-1):
        p = int(parsed_lines[i][0])
        x = int(parsed_lines[i][1])
        P.append(p)
        X.append(x)

    # S = parsed_lines[1][0]
    # return n, k, S
    return n, q, A, B, P, X


if not do_submit:
    n, q, A, B, P, X = input_parse("""
    4 3
    1 2
    2 3
    2 4
    2 10
    1 100
    3 1
    """)
    print(sol(n, q, A, B, P, X))

    n, q, A, B, P, X = input_parse("""
        6 2
        1 2
        1 3
        2 4
        3 6
        2 5
        1 10
        1 10
    """)
    print(sol(n, q, A, B, P, X))

    n, q, A, B, P, X = input_parse("""
        10 5
        1 2
        1 3
        1 4
        2 5
        2 6
        3 7
        4 8
        4 9
        7 10
        7 3
        3 100
        1 2
        5 10
        4 11
    """)
    print(sol(n, q, A, B, P, X))

else:
    n, q = list(map(int, input().split()))
    trees =  [ [] for i in range(n) ]
    values = [ 0 for i in range(n) ]
    for i in range(n-1):
        a, b = list(map(int, input().split()))
        trees[a-1].append(b-1)
        trees[b-1].append(a-1)
    for i in range(q):
        p, x = list(map(int, input().split()))
        # dfs, give point x
        values[p-1] += x
    print(values)
    # accmulative run
    def dfs2(i, parent):
        for j in trees[i]:
            if j == parent: continue
            values[j] += values[i]
            dfs2(j, i)
    dfs2(0, -1)
    #
    for x in values:
        print(x, end=" ")
    print("")

Submission status: Runtime Error

Solution code:
class TreeNode:
    def __init__(self):
        self.val = 0
        self.vertex = []


def make_trees(n, A, B):
    trees = []
    for i in range(n):
        trees.append(TreeNode())
    for i in range(len(A)):
        a = A[i]-1
        b = B[i]-1
        trees[a].vertex.append(b)
    return trees

def dfs(node: TreeNode, carry: int, trees):
    if node:
        node.val += carry
        for i in node.vertex:
            dfs(trees[i], node.val, trees)

def sol(n, q, A, B, P, X):
    trees = make_trees(n, A, B)
    for i in range(len(P)):
        p = P[i]-1
        x = X[i]
        t = trees[p]
        # dfs, give point x
        t.val += x
    # accmulative run
    dfs(trees[0], 0, trees)
    #
    return " ".join([str(t.val) for t in trees])
    #return n, q, A, B, P, X



do_submit = True
#do_submit = False

def input_parse(input_str):
    lines = [x.strip() for x in input_str.split("\n") if x.strip()]
    parsed_lines = [list(map(str, line.split())) for line in lines]
    print(parsed_lines)
    n = int(parsed_lines[0][0])
    q = int(parsed_lines[0][1])
    A = []
    B = []
    P = []
    X = []
    for i in range(1, n-1+1):
        a = int(parsed_lines[i][0])
        b = int(parsed_lines[i][1])
        A.append(a)
        B.append(b)
    for i in range(n, 1+n+q-1):
        p = int(parsed_lines[i][0])
        x = int(parsed_lines[i][1])
        P.append(p)
        X.append(x)

    # S = parsed_lines[1][0]
    # return n, k, S
    return n, q, A, B, P, X


if not do_submit:
    n, q, A, B, P, X = input_parse("""
    4 3
    1 2
    2 3
    2 4
    2 10
    1 100
    3 1
    """)
    print(sol(n, q, A, B, P, X))

    n, q, A, B, P, X = input_parse("""
        6 2
        1 2
        1 3
        2 4
        3 6
        2 5
        1 10
        1 10
    """)
    print(sol(n, q, A, B, P, X))

    n, q, A, B, P, X = input_parse("""
        10 5
        1 2
        1 3
        1 4
        2 5
        2 6
        3 7
        4 8
        4 9
        7 10
        7 3
        3 100
        1 2
        5 10
        4 11
    """)
    print(sol(n, q, A, B, P, X))

else:
    n, q = list(map(int, input().split()))
    trees =  [ [] for i in range(n) ]
    values = [ 0 for i in range(n) ]
    for i in range(n-1):
        a, b = list(map(int, input().split()))
        trees[a-1].append(b-1)
        trees[b-1].append(a-1)
    for i in range(q):
        p, x = list(map(int, input().split()))
        # dfs, give point x
        values[p-1] = values[p-1] + x
    # accmulative run
    def dfs2(i, parent):
        for j in trees[i]:
            if j == parent: continue
            values[j] += values[i]
            dfs2(j, i)
    dfs2(0, -1)
    #
    for x in values:
        print(x, end=" ")

Submission status: Runtime Error

Solution code:
# coding:utf-8


def main():
    N, Q = map(int, input().split())
    # A = []
    # B = []
    countList = [0]*N
    treeEdge = [[] for i in range(N)]

    for i in range(N-1):
        Ai, Bi = map(int, input().split())
        Ai -= 1
        Bi -= 1
        treeEdge[Ai].append(Bi)
        treeEdge[Bi].append(Ai)

    for i in range(Q):
        pi, xi = map(int, input().split())
        countList[pi - 1] += xi

    countList = addCount(0, -1, treeEdge, countList)

    for ci in countList:
        print(ci, end=" ")

    print()
    return


def addCount(index, parent, treeEdge, countList):
    if parent == -1:
        pass
    else:
        countList[index] += countList[parent]

    nextlist = treeEdge[index]

    if not len(nextlist) > 0:
        return countList
    else:
        for child in nextlist:
            if not child == parent:
                countList = addCount(child, index, treeEdge, countList)
    return countList


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import pprint

def comp2(num, ll, sl, check):
    if check[num] == 1:
        return sl
    else:
        check[num] = 1
        sl[num].add(num)
        for i in ll[num]:
            sl[num] = sl[num] | (comp2(i, ll, sl, check))[i]
            '''print("num ", num, " i ", i)
            print("sl ", sl)'''
        return sl


def solve():
    n, q = map(int, input().split())
    l = [[0] for i in range(n+1)]
    check = [0 for i in range(n+1)]
    group = [set() for i in range(n+1)]
    ans = [0]*(n+1)
    points = [0 for i in range(n+1)]
    for i in range(n-1):
        a, b = map(int, input().split())
        l[a].append(b)
    for i in range(1,n+1):
        group = comp2(i,l,group,check)
    for i in range(q):
        num, point = map(int, input().split())
        points[num] += point
    for i in range(1,n+1):
        li = list(group[num])
        for j in li:
            ans[j] += points[i]
    ans2 = list(map(str, ans))
    ans3 = ' '.join(ans2[1::])
    print(ans3)


if __name__=="__main__":
    solve()

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(500000)
n,q=map(int,input().split())
edge=[[] for i in range(n)]
cost=[0]*n
for i in range(n):
  p,s=map(int,input().split())
  p-=1;s-=1
  edge[p].append(s)
for i in range(q):
  x,c=map(int,input().split())
  x-=1
  cost[x]+=c
for i in range(n):
  for j in edge[i]:
    cost[j]+=cost[i]
for i in cost:
  i=str(i)
print(" ".join(cost))

Submission status: Runtime Error

Solution code:
n,q=map(int,input().split())
edge=[[] for i in range(n)]
cost=[0]*n
for i in range(n):
  p,s=map(int,input().split())
  p-=1;s-=1
  edge[p].append(s)
for i in range(q):
  x,c=map(int,input().split())
  x-=1
  cost[x]+=c
for i in range(n):
  for j in edge[i]:
    cost[j]+=cost[i]
for i in cost:
  i=str(i)
print(" ".join(cost))

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

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

ans = defaultdict(int)
ans[1] = operations[1]

def func(node,p_node):
    ans[node] = ans[p_node] + operations[node]
    connection[node].remove(p_node)
    for c_node in connection[node]:
        func(c_node, node)

for node in connection[1]:
    func(node, 1)

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

Submission status: Runtime Error

Solution code:
class TreeNode:
    def __init__(self):
        self.val = 0
        self.vertex = []


def make_trees(n, A, B):
    trees = []
    for i in range(n):
        trees.append(TreeNode())
    for i in range(len(A)):
        a = A[i]-1
        b = B[i]-1
        trees[a].vertex.append(b)
    return trees

def dfs(node: TreeNode, carry: int, trees):
    if node:
        node.val += carry
        for i in node.vertex:
            dfs(trees[i], node.val, trees)

def sol(n, q, A, B, P, X):
    trees = make_trees(n, A, B)
    for i in range(len(P)):
        p = P[i]-1
        x = X[i]
        t = trees[p]
        # dfs, give point x
        t.val += x
    # accmulative run
    dfs(trees[0], 0, trees)
    #
    return " ".join([str(t.val) for t in trees])
    #return n, q, A, B, P, X



do_submit = True
#do_submit = False

def input_parse(input_str):
    lines = [x.strip() for x in input_str.split("\n") if x.strip()]
    parsed_lines = [list(map(str, line.split())) for line in lines]
    print(parsed_lines)
    n = int(parsed_lines[0][0])
    q = int(parsed_lines[0][1])
    A = []
    B = []
    P = []
    X = []
    for i in range(1, n-1+1):
        a = int(parsed_lines[i][0])
        b = int(parsed_lines[i][1])
        A.append(a)
        B.append(b)
    for i in range(n, 1+n+q-1):
        p = int(parsed_lines[i][0])
        x = int(parsed_lines[i][1])
        P.append(p)
        X.append(x)

    # S = parsed_lines[1][0]
    # return n, k, S
    return n, q, A, B, P, X


if not do_submit:
    n, q, A, B, P, X = input_parse("""
    4 3
    1 2
    2 3
    2 4
    2 10
    1 100
    3 1
    """)
    print(sol(n, q, A, B, P, X))

    n, q, A, B, P, X = input_parse("""
        6 2
        1 2
        1 3
        2 4
        3 6
        2 5
        1 10
        1 10
    """)
    print(sol(n, q, A, B, P, X))

    n, q, A, B, P, X = input_parse("""
        10 5
        1 2
        1 3
        1 4
        2 5
        2 6
        3 7
        4 8
        4 9
        7 10
        7 3
        3 100
        1 2
        5 10
        4 11
    """)
    print(sol(n, q, A, B, P, X))

else:
    n, q = list(map(int, input().split()))
    trees =  [ [] for i in range(n) ]
    values = [ 0 for i in range(n) ]
    for i in range(n-1):
        a, b = list(map(int, input().split()))
        trees[a-1].append(b-1)
    for i in range(q):
        p, x = list(map(int, input().split()))
        # dfs, give point x
        values[p-1] = values[p-1] + x
    # accmulative run
    def dfs2(i):
        for j in trees[i]:
            values[j] += values[i]
            dfs2(j)
    dfs2(0)
    #
    for x in values:
        print(x, end=" ")

Submission status: Runtime Error

Solution code:
# coding:utf-8


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

    for i in range(N-1):
        Ai, Bi = map(int, input().split())
        treeEdge[Ai-1].append(Bi)
        treeEdge[Bi-1].append(Ai)

    for i in range(Q):
        pi, xi = map(int, input().split())
        countList[pi - 1] += xi

    countList = addCount(1, 0, treeEdge, countList)

    for ci in countList:
        print(ci, end=" ")

    print()
    return


def addCount(index, parent, treeEdge, countList):
    if parent == 0:
        pass
    else:
        countList[index-1] += countList[parent-1]

    nextlist = treeEdge[index-1]

    if not len(nextlist) > 0:
        return countList
    else:
        for child in nextlist:
            if not child == parent:
                countList = addCount(child, index, treeEdge, countList)
    return countList


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
def make_tree(N, ab):
    d = {i: [] for i in range(1, N + 1)}
    d[1] = [1]
    leaf = [i for i in range(1, N + 1)]
    for a, b in ab:
        if a in leaf:
            leaf.remove(a)
    ba = {b: a for a, b in ab}
    for l in leaf:
        temp = []
        h = l
        while (True):
            if (1 in d[h]):
                for x in temp:
                    d[x] += d[h]
                break
            else:
                temp += [h]
                for x in temp:
                    d[x] += [h]
                h = ba[h]
    return d


def calc(N, Q, ab, px):
    tree = make_tree(N, ab)
    ops = {i: 0 for i in range(1, N + 1)}
    for p, x in px:
        ops[p] += x
    result = []
    for i in tree:
        result += [sum([ops[j] for j in tree[i]])]
    return ' '.join([str(x) for x in result])


(N, Q) = tuple([int(s) for s in input().split(' ')])
ab = [tuple([int(s) for s in input().split(' ')]) for _ in range(N - 1)]
px = [tuple([int(s) for s in input().split(' ')]) for _ in range(Q)]
print(calc(N, Q, ab, px))

Submission status: Runtime Error

Solution code:
import pprint

def comp2(num, ll, sl, check):
    if check[num] == 1:
        return sl
    else:
        check[num] = 1
        sl[num].add(num)
        for i in ll[num]:
            sl[num] = sl[num] | (comp2(i, ll, sl, check))[i]
            '''print("num ", num, " i ", i)
            print("sl ", sl)'''
        return sl


def solve():
    n, q = map(int, input().split())
    l = [[0] for i in range(n+1)]
    check = [0 for i in range(n+1)]
    group = [set() for i in range(n+1)]
    ans = [0]*(n+1)
    for i in range(n-1):
        a, b = map(int, input().split())
        l[a].append(b)
    for i in range(1,n+1):
        group = comp2(i,l,group,check)
    for i in range(q):
        num, point = map(int, input().split())
        li = list(group[num])
        li = list(set(li))
        for j in li:
            ans[j] += point
    ans2 = list(map(str, ans))
    ans3 = ' '.join(ans2[1::])
    print(ans3)


if __name__=="__main__":
    solve()