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:
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 dfs2(carry, i, trees, values):
    values[i] += carry
    for j in trees[i]:
        dfs2(values[i], j, trees, values)

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
    dfs2(0, 0, trees, values)
    #
    for x in values:
        print(x, end=" ")

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

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': []})

for p, x in p_x_list:
    gen = dfs_generator(nodes, p)
    try:
        while True:
            nodes[next(gen)]['val'] += x
    except StopIteration:
        pass

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:
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 dfs2(carry, i, trees, values):
    values[i] += carry
    for j in trees[i]:
        dfs2(values[i], j, trees, values)

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
    dfs2(0, 0, trees, values)
    #
    print(values)

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10**18)

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

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

Submission status: Runtime Error

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

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

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

Submission status: Runtime Error

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

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

Submission status: Runtime Error

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

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

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


def d(y, parent):
    for k in ki[y]:
        if k == parent:
            continue
        cnt[k] += cnt[y]
        d(k, y)


d(1, -1)
print(*cnt[1:])

Submission status: Runtime Error

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

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

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


def d(y, parent):
    for i in ki[y]:
        if i == parent:
            continue
        cnt[i] += cnt[y]
        d(i, y)


d(1, -1)
print(*cnt[1:])

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

marked = []
def dfs(i):
  marked.append(i)
  for c in nodes[i]:
    if c not in marked:
      values[c] += values[i]
      dfs(c)

dfs(0)
print(*values)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
N, Q = map(int, input().split())

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

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

ans = [0]
ans[0] = xs[0]
visited = [0]*N
stack = [0]
while stack:
    v = stack.pop()
    visited[v] = 1
    for to in es[v]:
        if visited[to]:
            continue
        stack.append(to)
        ans[to] = ans[v] + xs[to]

print(*ans)

Submission status: Runtime Error

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

#=====================================
class Tree():
  def __init__(self, n):
    self.children = []
    self.counter = 0

  def add_child(self, child):
    self.children += [child]
  
  def reconstruct(self, root=None):
    if root in self.children:
      self.children.remove(root)
    for child in self.children:
      child.reconstruct(self)
  
  def add_count(self, x):
    self.counter += x
    for child in self.children:
      child.add_count(x)

#=====================================
      
trees = [Tree(i) for i in range(n)]

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

trees[0].reconstruct()

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

print(*[trees[i].counter for i in range(n)])

Submission status: Runtime Error

Solution code:
def make_tree(ab, parent):
    e_parent = []
    e_else = []
    for a, b in ab:
        if (a == parent):
            e_parent += [b]
        else:
            e_else += [(a, b)]
    children = []
    for b in e_parent:
        r = make_tree(e_else, b)
        if (type(r[0]) == tuple):
            children += [r[0]]
            e_else = r[1]
        else:
            children += [r]
            e_else = []
    if (e_else):
        return ((parent, children), e_else)
    else:
        return (parent, children)


def add_tree(tree, ops):
    x = ops[tree[0]] if tree[0] in ops else 0
    for c in tree[1]:
        ops[c[0]] = x + (ops[c[0]] if c[0] in ops else 0)
        ops = add_tree(c, ops)
    return ops


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


(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 sys
from collections import deque, defaultdict
import copy
import bisect
input=sys.stdin.readline
#sys.setrecursionlimit(10 ** 9)
import math
import heapq


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

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

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

Submission status: Runtime Error

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


N, Q = list(map(int, input().split()))
eda = [[] for i in range(N)]
ope = [0]*N
score = [0]*N
parent = [-1]*N


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

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


que = []
que.append(0)
score[0] = ope[0]
for ss in range(N - 1):
	loc = que.pop()
	for edge in eda[loc]:
		if parent[loc] != edge:
			score[edge] += score[loc] + ope[edge]
			que.append(edge)
			parent[edge] = loc

for i in range(N - 1):
	print(score[i], end = "")
	print(" ", end = "")
print(score[N - 1])

Submission status: Runtime Error

Solution code:
    import sys
    sys.setrecursionlimit(10**6)
     
    n, q = map(int, input().split())
    g = [[] for _ in range(n)]
    for i in range(n-1):
      a, b = map(int, input().split())
      a, b = a-1, b-1
      g[a].append(b)
      #g[b].append(a)
     
    ans = [0]*n  
    for j in range(q):
      p, x = map(int, input().split())
      ans[p-1] += x
      
    from collections import deque
    s = deque()
    s.append(0)
     
    while s:
      v = s.pop()
      for v_ in g[v]:
        ans[v_] += ans[v]
        s.append(v_)
     
    print(' '.join(map(str, ans)))

Submission status: Runtime Error

Solution code:
class Node(object):
    def __init__(self, vertex, counter, parent = None):
        self.vertex = vertex
        self.counter = counter
        self.parent = parent
        self.siblings = []  # dict()


class Tree(object):
    def __init__(self, root):
        self.root = Node(root, 0)
        self.size = 1
        self.current = self.root
        self.nodes = {self.root.vertex: self.root}

    def add_child(self, target, value):
        parent = self.nodes[target]
        child = Node(value, 0, parent)
        parent.siblings.append(child)
        self.nodes[value] = child

    def increment(self, target, count):
        node = self.nodes[target]
        stack = [node]
        while stack:
            sb = stack.pop()
            sb.counter += count
            for i in sb.siblings:
                stack.append(i)

l1 = list(map(int, input().split()))
n = l1[0]
q = l1[1]
tree = Tree(1)
# build tree
for i in range(n - 1):
    li = list(map(int, input().split()))
    target = li[0]
    value = li[1]
    tree.add_child(target, value)

# operation
for i in range(q):
    li = list(map(int, input().split()))
    target = li[0]
    counter = li[1]
    tree.increment(target, counter)

queue = [tree.root]
while queue:
    q = queue.pop(0)
    print(q.counter, end=" ")
    for n in q.siblings:
        queue.append(n)