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: Accepted

Solution code:
from collections import deque


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


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



visited = [0] * n
visited[0] = 1
que = deque([0])

while que:
    cur = que.popleft()
    for nxt in graph[cur]:
        if visited[nxt]:
            continue
        cost[nxt] += cost[cur]
        que.append(nxt)
        visited[nxt] = 1


print(*cost)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
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

todo = [1]
seen = [False] * (n+1)
while todo:
  p = todo.pop(-1)
  ct[p] += o[p]
  seen[p] = True
  for i in g[p]:
    if seen[i]:
      ct[p] += ct[i]
    else:
      todo.append(i)

print(*ct[1:])

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
def main():
    N,Q = map(int,input().split())
    X = [list(map(int,input().split())) for _ in range(N-1)]
    Y = [list(map(int,input().split())) for _ in range(Q)]

    con = [[] for _ in range(N)]
    for i in range(N-1):
        con[X[i][0]-1]+=[X[i][1]-1]
        con[X[i][1]-1]+=[X[i][0]-1]

    dif = [0]*N
    for i in range(Q):
        dif[Y[i][0]-1] += Y[i][1]

    root = [0]
    while root:
        cur = root.pop()
        for i in con[cur]:
            dif[i] += dif[cur]
            con[i].remove(cur)
            root.append(i) 
    print(*dif)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

def solve():
  n,q = (int(i) for i in input().split())
  graph = [[] for _ in range(n)]

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

  query = deque([(0,-1)])
  while query:
    nowplace,parent = query.popleft()
    nowvalue = ans[nowplace]   
    for node in graph[nowplace]:
      if node == parent:
        continue
      else:
        ans[node] += nowvalue
        query.append([node,nowplace])
      
  print(*ans)

if __name__ == '__main__':
  solve()

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

def solve():
  n,q = (int(i) for i in input().split())
  graph = [[] for _ in range(n)]

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

  query = [(0,-1)]
  while query:
    nowplace,parent = query.pop()
    nowvalue = ans[nowplace]   
    for node in graph[nowplace]:
      if node == parent:
        continue
      else:
        ans[node] += nowvalue
        query.append([node,nowplace])
      
  print(*ans)
  
solve()

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

def solve():
  n,q = (int(i) for i in input().split())
  graph = [[] for _ in range(n)]

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

  query = deque([(0,-1)])
  while query:
    nowplace,parent = query.popleft()
    nowvalue = ans[nowplace]   
    for node in graph[nowplace]:
      if node == parent:
        continue
      else:
        ans[node] += nowvalue
        query.append([node,nowplace])
      
  print(*ans)
  
solve()

Submission status: Accepted

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


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

Submission status: Accepted

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


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

Submission status: Accepted

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


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

Submission status: Accepted

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


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

Submission status: Accepted

Solution code:
from collections import deque


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


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

Submission status: Accepted

Solution code:
from collections import deque


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


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

Submission status: Accepted

Solution code:
import sys

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


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

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

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

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline #for input speed
sys.setrecursionlimit(10**6) #for deep recursion
n, q = map(int, input().split())
 
tree_index = [[] for _ in range(n)]
for i in range(n-1):
  a,b = map(int, input().split())
  a -= 1
  b -= 1
  tree_index[a].append(b) # a<bとは限らないため、双方向にする
  tree_index[b].append(a)
ans = [0] * n
for i in range(q):
  p, x = map(int, input().split())
  ans[p-1] += x
def dfs(cur, par):
    for chl in tree_index[cur]:
      if chl == par: #parentとchildが等しい時はとばす
        continue
      ans[chl] += ans[cur] 
      dfs(chl, cur)
dfs(0, -1)
print(*ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
n, q = map(int, input().split())
 
stack = [[] for _ in range(n)]
for i in range(n-1):
  a,b = map(int, input().split())
  a -= 1
  b -= 1
  stack[a].append(b)
  stack[b].append(a)
ans = [0] * n
for i in range(q):
  p, x = map(int, input().split())
  ans[p-1] += x
def dfs(cur, par):
    for c in stack[cur]:
      if c == par:
        continue
      ans[c] += ans[cur] 
      dfs(c, cur)
dfs(0, -1)
print(*ans)

Submission status: Accepted

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

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

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

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

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

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

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

    parent_nodes = deque()
    parent_nodes.append(0)
    visited_nodes = set()
    while parent_nodes:
        parent = parent_nodes.popleft()
        if parent in visited_nodes:
            continue
        visited_nodes.add(parent)
        for child in edges[parent]:
            if child in visited_nodes:
                continue
            counts[child] += counts[parent]
            parent_nodes.append(child)

    print(' '.join(list(map(str, counts))))

if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

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

dfs(1, 0, 0)

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

Submission status: Accepted

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

ANS = [0] * (n+1)

C_plus = [0] * (n+1)
for i in range(q):
    C_plus[P[i][0]] += P[i][1]

E = [[] for i in range(n+1)]
V = [0] * (n+1)
Q = [0] * (n+2)
Q[0] = 1
t = 0
r = 1

V[1] = 1
ANS[1] = C_plus[1]

for i in range(n-1):
    E[A[i][0]].append(A[i][1])
    E[A[i][1]].append(A[i][0])

def tansaku(x):
    global r
    for i in E[x]:
        if V[i] == 0:
            ANS[i] = C_plus[i] + ANS[x]
            V[i] = 1
            Q[r] = i
            r += 1
            #print(Q)

while t != r:
    tansaku(Q[t])
    t += 1

#print(ANS)

for i in range(n+1):
    ANS[i] = str(ANS[i])
print(" ".join(ANS[1:]))

Submission status: Accepted

Solution code:
from collections import deque
n,q=map(int, input().split())
l=[[] for i in range(n+1)]
ans=[0]*(n+1)

for i in range(n-1):
    a,b=[int(j) for j in input().split()]
    l[a].append(b)
    l[b].append(a)
for i in range(q):
    p,x=[int(j) for j in input().split()]
    ans[p]+=x

que=deque()
que.append(1)
ll=[0]*(n+1)
while que:
    y=que.popleft()
    ll[y]=1
    for i in l[y]:
        if ll[i]==1:
            continue
        ans[i]+=ans[y]
        que.append(i)
print(*ans[1:])

Submission status: Accepted

Solution code:
from collections import deque
n,q=map(int, input().split())
l=[[] for i in range(n+1)]
ans=[0]*(n+1)

for i in range(n-1):
    a,b=[int(j) for j in input().split()]
    l[a].append(b)
    l[b].append(a)
for i in range(q):
    p,x=[int(j) for j in input().split()]
    ans[p]+=x

que=deque()
que.append(1)
ll=[0]*(n+1)
while que:
    y=que.popleft()
    ll[y]=1
    for i in l[y]:
        if ll[i]==1:
            continue
        ans[i]+=ans[y]
        que.append(i)
print(*ans[1:])

Submission status: Accepted

Solution code:
N, Q = list(map(int, input().split()))
d = {i: set() for i in range(1, N + 1)}
for i in range(N - 1):
    a, b = list(map(int, input().split()))
    d[a].add(b)
    d[b].add(a)
counter = [0] * (N + 1)
for _ in range(Q):
    p, x = list(map(int, input().split()))
    counter[p] += x

parents = {1}
while parents:
    children = set()
    for parent in parents:
        v = counter[parent]
        for child in d[parent]:
            d[child].remove(parent)
            children.add(child)
            counter[child] += v
    parents = children
print(*counter[1:])

Submission status: Accepted

Solution code:
# coding: utf-8
from collections import deque
N, Q = map(int, input().split())
lst = [[] for _ in range(N)]
ans = [0] * N
for i in range(N-1):
    a,b = map(int, input().split())
    lst[b-1].append(a-1)
    lst[a-1].append(b-1)
for j in range(Q):
    p, x = map(int, input().split())
    ans[p-1] += x

q = deque()
q.append(0)
flag = [0] * N
while q:
    y = q.pop()
    flag[y] = 1
    for k in lst[y]:
        if flag[k] == 1:
            continue
        ans[k] += ans[y]
        q.append(k)
print(*ans)

Submission status: Accepted

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

n,q = map(int, input().split())
G = [[] for i 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)


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

# bfs
from collections import deque
q = deque()
q.append((0,0))
visited = [0]*n
ans = [0]*n
while q:
    cur, cost = q.popleft()
    if visited[cur]:
        continue
    visited[cur] = 1
    cost += a[cur]
    ans[cur] = cost
    for to in G[cur]:
        if not visited[to]:
            q.append((to, cost))

print(*ans)