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:
import sys
sys.setrecursionlimit(10 ** 9)

input = sys.stdin.readline

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

ans = [0 for _ in range(n)]

visit = [False for _ in range(n)]
visit[0] = True

stack = []
stack.append((0, 0))

while stack:
    pos, val = stack.pop(-1)
    val += cnt[pos]
    ans[pos] = val
    for to in edges[pos]:
        if not visit[to]:
            visit[to] = True
            stack.append((to, val))

for x in ans[:-1]:
    print(x, end=' ')
print(ans[-1])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)

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

def func(p, now):
    global res
    res[p-1]+=px[p-1]+now
    for i in ab[p-1]:
        func(i, res[p-1])

res=[0]*n

func(1, 0)

print(" ".join(map(str, res)))

Submission status: Accepted

Solution code:
n, q = list(map(int, input().split(" ")))
a = []
b = []
tree = []

class Node:
    def __init__(self, id):
        self.id = id
        self.counter = 0
        self.linked = []

    def add_node(self, node):
        self.linked.append(node)

    def add_count(self, count):
        self.counter += count

# make node
for i in range(n):
    tree.append(Node(i))

# add node
for i in range(n-1):
    j, k = list(map(int, input().split(" ")))
    tree[j-1].add_node(tree[k-1])

# add count
for i in range(q):
    j, k = list(map(int, input().split(" ")))
    tree[j-1].add_count(k)

# traverse
for i in tree:
    for j in i.linked:
        j.counter += i.counter

m = []
for i in tree:
    m.append(i.counter)

print(" ".join(map(str, m)))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(300000)
input = sys.stdin.readline
n,q=map(int,input().strip().split())
d=[[] for _ in range(n)]

for _ in range(n-1):
    a,b=map(int,input().split())
    d[a-1].append(b-1)
    d[b-1].append(a-1)
l=[0]*n
for _ in range(q):
    a,b=map(int,input().split())
    l[a-1]+=b
rs=[0]*n

def rr(pa,s,dd,d):
    for c in d[s]:
        if c == pa:
            continue
        rs[c]=l[c]+dd
#        print(c,rs[c],dd)
        rr(s,c,dd+l[c],d)

s,dd=0,l[0]
rs[0] = l[0]
rr(None,s,dd,d)
for r in rs:
    print(r)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10**6)

n, q = map(int, sys.stdin.readline().strip().split())

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

plus = [0] * (n + 1)

for _ in range(q):
  p, x = map(int, sys.stdin.readline().strip().split())
  plus[p] += x

def calc(num, path, plus, parent):
  for i in path[num]:
    if i == parent:
      continue

    plus[i] += plus[num]
    calc(i, path, plus, num)

calc(1, path, plus, 0)

print(" ".join([str(i) for i in plus[1:]]))

Submission status: Accepted

Solution code:
from sys import stdin

def main():
    N, Q = map(int, input().split())
    AB = [tuple(map(int, input().split())) for _ in [0] * (N - 1)]
    PX = [tuple(map(int, input().split())) for _ in [0] * Q]

    AB.sort()
    point = [0] * (N + 1)
    for p, x in PX:
        point[p] += x

    for a, b in AB:
        point[b] += point[a]

    print(*point[1:])

input = lambda: stdin.readline()
main()

Submission status: Accepted

Solution code:
N,Q=map(int,input().split())
l=[[1,0,0]]
for i in range(1,N):
    a,b=map(int,input().split())
    l.append([b,a,0])
l.sort()
for i in range(Q):
    p,x=map(int,input().split())
    l[p-1][2]+=x
t=[l[0][2]]
for i in range(1,N):
    t.append(t[l[i][1]-1]+l[i][2])
print(*t)

Submission status: Accepted

Solution code:
N, Q = map(int, raw_input().split())
ans = [0 for i in range(N)]
tree_s = ['' for i in range(N-1)]

for i in range(0, N-1):
    a, b = map(int, raw_input().split())
    tree_s[i] = str(a).zfill(8) + '-' + str(b)

tree_s.sort()

for i in range(0, Q):
    v, p = map(int, raw_input().split())
    ans[v-1] += p

for i in range(0, N-1):
    ab = tree_s[i].split("-")
    ans[int(ab[1])-1] += ans[int(ab[0])-1]


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

Submission status: Accepted

Solution code:
N, Q = (int(x) for x in input().split())
a, b = [0]*(N-1), [0]*(N-1)
p, x = [0]*Q, [0]*Q
back_edge = [None]*N
counter = [0]*N
for i in range(N-1):
    a[i], b[i] = (int(x)-1 for x in input().split())
    back_edge[b[i]] = a[i]
for j in range(Q):
    p[j], x[j] = (int(x) for x in input().split())
    counter[p[j]-1] += x[j]
for i in range(N):
    if back_edge[i] is not None:
        counter[i] += counter[back_edge[i]]
else:
    print(*counter)

Submission status: Accepted

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

N, Q = map(int,input().split())
Node = [-1] * N
Counter = [0] * N
Result = [0] * N

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

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

for i in range(N):
    p = i
    ans = 0
    while p >= i:
        ans += Counter[p]
        p = Node[p]
    Result[i] = ans
    if p >= 0:
        Result[i] += Result[p]

print(" ".join(list(map(str,Result))))

Submission status: Accepted

Solution code:
from collections import defaultdict as dd
from collections import deque as dq
N, Q = map(int, input().split())
e = dd(list)
for _ in range(N - 1):
  u, v = map(int, input().split())
  e[u].append(v)
  e[v].append(u)
  
res = [0] * (N + 1)
for _ in range(Q):
  p, x = map(int, input().split())
  res[p] += x
visited = [0] * (N + 1)
Q = dq([])
Q.append(1)
visited[1] = 1
while len(Q) != 0:
  n = Q.pop()
  visited[n] = 1
  for o in e[n]:
    if visited[o] == 0:
      res[o] += res[n]
      Q.append(o)
#def dfs(n):
#  global visited
#  global res
#  visited[n] = 1
#  for o in e[n]:
#    if visited[o] == 0:
#      res[o] += res[n]
#      dfs(o)
#dfs(1)
sen = ""
for i in range(1, N + 1):
  sen += str(res[i])
  if i != N:
    sen += " "
print(sen)

Submission status: Accepted

Solution code:
N, Q = map(int, input().split())
order_dict = {}
ans = [0]*N

for i in range(N):
    if i != 0:
        a, b = map(int, input().split())
        if not a in order_dict:
            order_dict[a] = set()
        order_dict[a].add(b)
    

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

for a in range(N+1):
    if a in order_dict:
        for b in order_dict[a]:
            ans[b-1] += ans[a-1]


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

Submission status: Accepted

Solution code:
import collections

n,q=map(int,input().split())
a=sorted(list(list(map(int,input().split())) for i in range(n-1)))
p=collections.defaultdict(int)
for i in range(q):
  k,v=map(int,input().split())
  p[k]+=v

li=[0]*n
li[0]+=p[1]
for i in range(n-1):
  li[a[i][1]-1]+=li[a[i][0]-1]+p[a[i][1]]
print(*li)

Submission status: Accepted

Solution code:
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)]
ab.sort(key=lambda x: x[0])
ans = [0] * n

for i in px:
  ans[i[0] - 1] += i[1]

for i in ab:
  ans[i[1] - 1] += ans[i[0] - 1]
  
print(*ans)

Submission status: Accepted

Solution code:
from heapq import heappush, heappop, heapify, heapreplace
from collections import defaultdict
from bisect import bisect_left


class Solution:
    def main(self):
        path = defaultdict(list)
        N, Q = map(int, input().split())
        freq = [0] * N
        for i in range(N-1):
            ai, bi = map(int, input().split())
            path[ai-1].append(bi-1)
            # path[bi-1].append(ai-1)

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

        stack = [(0, 0)]
        seen = set()
        res = freq[:]
        for i in range(N):
            for other in path[i]:
                res[other] += res[i]

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


if __name__ == '__main__':
    Solution().main()

Submission status: Accepted

Solution code:
import sys
from collections import deque
def main():
    input=sys.stdin.readline
    n,q=map(int,input().split())

    edge=[[] for _ in range(n)]
    for _ in range(n-1):
        u,v=map(int,input().split())
        u-=1;v-=1
        edge[u].append(v)
   
    cost=[0]*n
    for _ in range(q):
        p,x=map(int,input().split())
        p-=1
        cost[p]+=x

    for idx,e in enumerate(cost):
        if e==0:continue
        for f in edge[idx]:
            cost[f]+=e

    print(*cost)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n,q=map(int,input().split())
d={i:[] for i in range(n)}
for i in range(n-1):
    a,b=map(int,input().split())
    d[a-1].append(b-1)
counter = [0 for i in range(n)]
for i in range(q):
    p,x=map(int,input().split())
    counter[p-1]+=x
for i in range(n-1):
    for child in d[i]:
        counter[child]+=counter[i]
print(' '.join(map(str, map(int,(counter)))))

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(300000)
input = sys.stdin.readline

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

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

Co = [0] * (N + 1)
import collections

q = collections.deque([(1, 0)])
while (len(q) > 0):
    now, pa = q.popleft()
    Co[now] = Ps[now] + Co[pa]
    for c in children[now]:
        q.append((c, now))

Co.pop(0)
print(" ".join(map(str, Co)))

Submission status: Accepted

Solution code:
#D
N, Q = map(int, input().split())
#digraph a -> b
score = [0 for i in range(0,N+1)]
edge = []
aba = edge.append
ope = []
pxa = ope.append
for _ in range(N-1):
    aba(tuple(map(int, input().split())))
edge.sort() #ascending order
for _ in range(Q):
    ope = tuple(map(int, input().split()))
    score[ope[0]] += ope[1] #id
for i in range(N-1):
    score[edge[i][1]] += score[edge[i][0]]
score.remove(score[0])
print(*score)

Submission status: Accepted

Solution code:
from collections import deque
from collections import defaultdict

def getlist():
	return list(map(int, input().split()))

class Graph(object):

    def __init__(self):
        self.graph = defaultdict(list)

    def __len__(self):
        return len(self.graph)

    def add_edge(self, a, b):
        self.graph[a].append(b)

G = Graph()

N, Q = getlist()
for i in range(N - 1):
	a, b = getlist()
	G.add_edge(a, b)
	G.add_edge(b, a)

plus = [0] * (N + 1)
for i in range(Q):
	p, x = getlist()
	plus[p] += x

q = deque([]) 
ans = [0] * N
visit = [-1] * (N + 1)
visit[1] = 1
q.append(1)
while q:
	m = q.pop()
	visit[m] = 1
	ans[m - 1] += plus[m]
	x = ans[m - 1]
	for i in G.graph[m]:
		if visit[i] == -1:
			q.append(i)
			ans[i - 1] += x

print(" ".join(list(map(str, ans))))

Submission status: Accepted

Solution code:
from sys import stdin

ntree = []
ans = []


n, q = [int(x) for x in stdin.readline().rstrip().split()]

for i in range(n):
    ntree.append([])
    ans.append(0)

for i in range(n-1):
  a, b = [int(x) for x in stdin.readline().rstrip().split()]
  ntree[a-1].append(b)

for i in range(q):
  p, x = [int(x) for x in stdin.readline().rstrip().split()]
  ans[p-1] += x

for i in range(n):
    for j in range(len(ntree[i])):
       ans[ntree[i][j]-1] += ans[i]

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

Submission status: Accepted

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

import sys
input = sys.stdin.readline

N, Q = map(int, input().split())
ab = [None] * (N - 1)
for i in range(N - 1):
    ab[i] = list(map(int, input().split()))
ab = sorted(ab, key=lambda x: (x[0], x[1]))

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

ans = [0] * N
ans[0] = px_n[0]
for (a, b) in ab:
    ans[b-1] += ans[a-1] + px_n[b-1]

print(*ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from heapq import heappush,heappop

n,q=map(int,input().split())
a=[]
for i in range(n-1):
    heappush(a,list(map(int,input().split())))
p=[0]*q
x=[0]*q
c=[0]*n
for _ in range(q):
    p,x=map(int,input().split())
    c[p-1]+=x
ans=[0]*n
ans[0]=c[0]
for _ in range(n-1):
    l=heappop(a)
    ans[l[1]-1]=ans[l[0]-1]+c[l[1]-1]
print(*ans)

Submission status: Accepted

Solution code:
from heapq import heappush,heappop

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

    hen = []
    for _ in range(n-1):
        a,b = map(int, input().split())
        heappush(hen,(a,b))

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

    # 操作はまとめられる。頂点nに対してpの和
    # 親から累積させながら末端へ下ろしていく

    while len(hen) > 0:
        a, b = heappop(hen)
        ns[b] += ns[a]

    print(*ns[1:n+1])
resolve()

Submission status: Accepted

Solution code:
from collections import defaultdict

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

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

val = defaultdict(int)
for p, x in [tuple(map(int, input().split())) for _ in range(Q)]:
    val[p] += x

ans = [0 for _ in range(N + 1)]

stack = list()
stack.append((0, -1, 0))
while len(stack) > 0:
    v, p, cnt = stack.pop()
    cnt += val[v]
    ans[v] = cnt
    for next_v in nl[v]:
        if next_v != p:
            stack.append((next_v, v, cnt))

print(' '.join([str(a) for a in ans[1:]]))

Submission status: Accepted

Solution code:
a,b=map(int,input().split())
y=[]
for i in range(a-1):
    v=list(map(int,input().split()))
    y.append(v)
y.sort(key=lambda n:n[0])
ans=[0]*a
for j in range(b):
    c,d=map(int,input().split())
    ans[c-1]=ans[c-1]+d
for k in range(a-1):
    ans[y[k][1]-1]=ans[y[k][1]-1]+ans[y[k][0]-1]
print(*ans,sep=" ")

Submission status: Accepted

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

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

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


dp = [-1 for _ in range(N + 1)]


dp[1] = points[1]

def search(target):
    if dp[target] != -1:
        return dp[target]

    parent = rtree[target]
    ppoint = search(parent)
    dp[target] = ppoint + points[target]
    return dp[target]

ans = []
for target in range(1, N+1):
    ans.append(search(target))

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

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     
def main():
    N, Q = LI()
    edge, P, X = [], [], []
    ans = [0 for _ in range(N)]
    for _ in range(N-1):
        _a, _b = LI()
        edge.append((_a-1, _b-1))
    edge = sorted(edge, key=lambda x:x[0])
    for _ in range(Q):
        _p, _x = LI()
        ans[_p-1] += _x
    for i in range(N-1):
        a_nodenum = edge[i][0]
        b_nodenum = edge[i][1]
        ans[b_nodenum] += ans[a_nodenum]
    for i in ans:
        print(i, end=" ")
    print()
main()

Submission status: Accepted

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

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

for _ in range(q):
    tmp1, tmp2 = map(int, input().split())
    x[tmp1] += tmp2

# 隣接リスト
l = [[] for _ in range(n+1)]
for pi in p:
    l[pi[0]].append(pi[1])
    l[pi[1]].append(pi[0])
p = [0] * (n+1)

import sys
sys.setrecursionlimit(10000000)


def dfs(n, v, par):
    p[n] = v
    for chl in l[n]:
        if chl == par:
            continue  # parent
        dfs(chl, v+x[chl], n)
    return

dfs(1, x[1], 0)
print(*p[1:])

Submission status: Accepted

Solution code:
import copy
n,q=map(int,input().split())
l=[]
for i in range(n-1):
  l.append(list(map(int,input().split())))
l2=[]
for i in range(q):
  l2.append(list(map(int,input().split())))
connection=[[] for i in range(n)]
for i in range(n-1):
  connection[l[i][0]-1].append(l[i][1]-1)

L4=[]
for i in range(n):
  L4.append(0)
for i in range(q):
  L4[l2[i][0]-1]+=l2[i][1]
distance=[0 for i in range(n)]
distance[0]=L4[0]
ans=[0 for i in range(n)]
ans[0]=L4[0]
L=[0]
L2=[]
L3=[]
while len(L2)!=n and len(L)!=0:
  for j in range(len(L)):
    for k in range(len(connection[L[j]])):
      distance[connection[L[j]][k]]=distance[L[j]]+L4[connection[L[j]][k]]
      L3.append(connection[L[j]][k])
    L2.append(L[j])
  L=copy.copy(L3)
  L3=[]
for i in range(len(distance)):
  distance[i]=str(distance[i])
print(' '.join(distance))

Submission status: Accepted

Solution code:
# coding: utf-8

import sys
import math
import collections
import itertools
def input(): return sys.stdin.readline().strip()
def gcd(x, y): return y if x % y == 0 else gcd(y, x % y)
def lcm(x, y): return (x * y) // gcd(x, y)
MOD = 10 **9 + 7

# N = int(input())
# S = input()
N, Q = map(int, input().split())
# 横
# L = [int(x) for x in input().split()]
# 縦
# A = [int(input()) for _ in range(N)]
# 多次元
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)]

AB.sort(key=lambda x : x[1])
PX.sort(key=lambda x : x[0])

S = [0] * (N + 1)
ab = 0
px = 0

for i in range(1, N + 1) :
    while px < Q and PX[px][0] == i :
        S[i] += PX[px][1]
        px += 1

    while ab < (N - 1) and AB[ab][1] == i :
        S[i] += S[AB[ab][0]]
        ab += 1
    
    print(S[i], end=" ")

print()

Submission status: Accepted

Solution code:
n, q = map(int, input().split())
pl = []
xl = []
parent = {}
for i in range(1, n):
    a, b = map(int, input().split())
    parent[b] = a
for i in range(q):
    p, x = map(int, input().split())
    pl.append(p)
    xl.append(x)

node = {}
for i in range(1, n+1):
    node[i] = 0
for j in range(q):
    node[pl[j]] += xl[j]


def find(parent, mem, node, i):
    if mem[i] != -1:
        return mem[i]
    if i == 1:
        mem[i] = node[i]
        return mem[i]
    mem[i] = node[i] + find(parent, mem, node, parent[i])
    return mem[i]


mem = [-1]*(n+1)
ans = []
for i in range(1, n+1):
    ans.append(find(parent, mem, node, i))
print(*ans)

Submission status: Accepted

Solution code:
import numpy as np
import math
import sys
sys.setrecursionlimit(10000000)

def main():
    N, Q = map(int, input().split())
    edges = {}
    for i in range(N-1):
        a, b = map(int, input().split())
        edges[b] = a # 子: 親

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

    qustions = sorted(questions.items(), key=lambda x:x[0])

    points = [0] * (N + 1)
    if questions.get(1) is None:
        points[1] = 0
    else:
        points[1] = questions[1]

    for i in range(2, N+1):
        if questions.get(i) is None:
            points[i] = points[edges[i]]
        else:
            points[i] = points[edges[i]] + questions[i]

    for i in range(1, N+1):
        print(points[i], end="")
        if i != N:
            print(end=" ")
    print("")



if __name__ == '__main__':
    main()

Submission status: Accepted

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

N, Q = list(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)]

class Tree:
  C = {}
  N, D = None, None
  def __init__(s, num):
    s.N = num
  def setC(s, a, b):
    if a in s.C: s.C[a].append(b)
    else: s.C[a] = [b]
    if b in s.C: s.C[b].append(a)
    else: s.C[b] = [a]
  def exe(s):
    L = [-1] * N
    A = [0] * N
    for p, x in px:
      p -= 1
      A[p] += x
    S = [0]
    while S != []:
      t = S.pop()
      L[t] = 1
      for i in s.C[t]:
        if L[i] == -1:
          L[i] = 1
          A[i] += A[t]
          S.append(i)
    for i in range(N):
      print(A[i], end = " ")

T = Tree(N)
for a, b in ab:
  a -= 1
  b -= 1
  T.setC(a, b)

T.exe()

Submission status: Accepted

Solution code:
n, q = (int(_) for _ in input().split())
res = [0] * n
l = [[] for i in range(n-1)]
for i in range(n-1):
    a, b = (int(_) for _ in input().split())
    l[a-1].append(b)
p = [list(map(int, input().split())) for i in range(q)]

for i in p:
    res[i[0]-1] += i[1]
for i in range(n-1):
    for ii in l[i]:
        res[ii-1] += res[i]

[print(i,end=" ") for i in res]
print()

Submission status: Accepted

Solution code:
import sys
MAX_INT = int(10e10)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

def init(n):
  for i in range(N):
    par[i]=i
    num[i]=0
def find(x):
  if par[x]==x:
    return x
  else:
    return find(par[x])
def unite(x,y):
  if (y<x):
    par[x]=y
  else:
    par[y]=x
def same(x,y):
  return find(x)==find(y)
def cnt(x):
  if par[x]==x:
    res = num[x]
    return res
  else:
    if used[par[x]] == True:
      res = num[x] + ans[par[x]]
      return res
    else:
      return

N,Q = IL()
ab = [IL() for i in range(N-1)]
px = [IL() for i in range(Q)]

par=[0 for i in range(N+1)]
num=[0 for i in range(N+1)]

init(N)

for a,b in ab:
  unite(a,b)

for p,x in px:
  num[p] += x

ans = [0 for i in range(N+1)]
used = [False for i in range(N+1)]
for i in range(1,N+1):
  ans[i] = cnt(i)
  used[i] = True

print(" ".join(map(str,ans[1:])))

Submission status: Accepted

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

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

Tree_sorted = sorted(Tree, key=lambda x:x[0])

P = []
X = []
for _ in range(Q):
    p, x = map(int, input().split())
    P.append(p)
    X.append(x)

scores = [0 for _ in range(N + 1)]
for i in range(Q):
    scores[P[i]] += X[i]

for tree in Tree_sorted:
    scores[tree[1]] += scores[tree[0]]

for i, score in enumerate(scores):
    if i == 0:
        continue
    print(score, end=' ')

Submission status: Accepted

Solution code:
N ,Q = map(int,input().split())
A =[]
B =[]
P =[]
X =[]
node_child = [[] for i in range(N)]
node_score = [[] for i in range(N)]
for i in range(N-1):
    a,b = map(int,input().split())
    A.append(a)
    B.append(b)
for i in range(Q):
    p,x = map(int,input().split())
    P.append(p)
    X.append(x)
for i in range(N-1):
    node_child[A[i]-1].append(B[i])
for i in range(Q):
    node_score[P[i]-1].append(X[i])
score = [0]*N

for i in range(N):
    score[i] += sum(node_score[i])
    for j in node_child[i]:
        score[j-1] += score[i]
for i in score:
    print('{0} '.format(i),end='' )

Submission status: Accepted

Solution code:
import math
from functools import reduce
from collections import deque
import sys
sys.setrecursionlimit(10**7)

def s(generator, splitter, mapper):
    return [ mapper(s) for s in generator().split(splitter) ]

# スペース区切りの入力を読み込んで数値リストにして返します。
def get_nums_l():
    return [ int(s) for s in input().split(" ")]

# 改行区切りの入力をn行読み込んで数値リストにして返します。
def get_nums_n(n):
    return [ int(input()) for _ in range(n)]

n,q = get_nums_l()

lines = sys.stdin.readlines()
edges = list(map(lambda s:list(map(int, s.split(" "))), lines[:n-1]))
queries = list(map(lambda s:list(map(int, s.split(" "))), lines[n-1:]))

scores = [0] * (n+1)

for q in queries:
    scores[q[0]] += q[1]

queue = deque()
mark = [False] * (n+1)
mark[1] = True


childrens = [ [] for _ in range(n+1) ]
for e in edges:
    a = e[0]
    b = e[1]
    childrens[a].append(b)
    childrens[b].append(a)


queue.append(1)

while queue:
    a = queue.popleft()
    children = childrens[a]
    for b in children:
        if not mark[b]:
            scores[b] += scores[a]
            mark[b] = True
            queue.append(b)

print(" ".join(map(str,scores[1:])))

Submission status: Accepted

Solution code:
N,Q = map(int,input().split())
parents = {1:0}
for _ in range(N-1):
    a,b = map(int,input().split())
    key,val = max(a,b), min(a,b)
    parents[key] = val
counts = [0]*(N+1)
for _ in range(Q):
    p,x = map(int,input().split())
    counts[p] += x
results = [0]*(N+2)
for i in range(1,N+1):
    results[i] = counts[i]+results[parents[i]]
    print(results[i], end=' ')

Submission status: Accepted

Solution code:
N, Q = map(int,input().split()) # 複数の数字を変数に格納
List_ab = [list(map(int,input().split())) for i in range(N-1)] # [[1,2],[3,4],[5,6]]
List_px = [list(map(int,input().split())) for i in range(Q)] # [[1,2],[3,4],[5,6]]

count_list = [0]*N

List_ab.sort()

for i in range(Q):
    count_list[List_px[i][0]-1] += List_px[i][1]
        
for i in range(N-1):
    count_list[List_ab[i][1]-1] += count_list[List_ab[i][0]-1]
    
print(*count_list)

Submission status: Accepted

Solution code:
import collections

n, q = map(int, input().split())
nxts = collections.defaultdict(list)
score = [0] * n 
for _ in range(n - 1):
    a, b = map(int, input().split())
    nxts[a - 1].append(b - 1)
    nxts[b - 1].append(a - 1)
for i in range(q):
    p, x = map(int, input().split())
    score[p - 1] += x


stack = [(0, -1)]
while stack:
    node, parent = stack.pop()
    for nxt in nxts[node]:
        if nxt != parent:
            score[nxt] += score[node]
            stack.append((nxt, node))

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

Submission status: Accepted

Solution code:
N, Q = map(int, input().split())
tree = [[] for i in range(N)]
for i in range(N-1):
    ai, bi = map(int, input().split())
    ai -= 1
    bi -= 1
    tree[ai].append(bi)
point = [0] * N
for j in range(Q):
    pi, xi = map(int, input().split())
    pi -= 1
    point[pi] += xi

answer = [0] * N
queue = []
counter = 0
queue.append((0, 0))
while True:
    if counter == len(queue):
        break
    node, p = queue[counter]
    counter += 1


    answer[node] = p + point[node]
    for t in tree[node]:
        queue.append((t, answer[node]))

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

Submission status: Accepted

Solution code:
from collections import deque

N, Q = list(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)]

points = [0 for _ in range(N+1)]
g = [[] for _ in range(N+1)]
for a, b in AB:
    g[a].append(b)

# print(g)

for p, x in PX:
    points[p] += x

q = deque([1])
while q:
    node = q.popleft()
    for child in g[node]:
        points[child] += points[node]
        q.append(child)

for point in points[1:]:
    print(point)

Submission status: Accepted

Solution code:
import collections

def main():
    N, Q = map(int, input().split())

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

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

    vals = [0 for _ in range(N)]
    v = 0
    if 1 in ops: v = ops[1]
    cur = [[1, v]]

    while cur:
        temp = []
        for a, v in cur:
            vals[a-1] += v
            for b in graph[a]:
                temp.append([b, v+ops[b]])
        cur = temp

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

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from sys import stdin
N, Q = list(map(int, stdin.readline().rstrip().split(' ')))
edge = [list(map(int, stdin.readline().rstrip().split(' '))) for _ in range(N-1)]
vals = [list(map(int, stdin.readline().rstrip().split(' '))) for _ in range(Q)]

res = [0] * N
for i, v in vals:
    res[i-1] = res[i-1] + v

edge.sort()
for p, d in edge:
    res[d-1] = res[d-1] + res[p-1]

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

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



par = [0] * n
que = deque([0])

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





print(*cost)

Submission status: Accepted

Solution code:
n,q = map(int,input().split())
sco = [0]*(n+1)
edge = [[i] for i in range(n+1)]

def dfs(i,s):
    E = edge[i]
    if(len(E)==1):
        return 0
    for e in E:
        if(e==i):continue
        sco[e]+=s
        dfs(e,s)

for i in range(n-1):
    a,b = map(int,input().split())
    edge[b].append(a)
#print(edge)
for i in range(q):
    p,x=map(int,input().split())
    sco[p]+=x
for i in range(1,n+1):
    E=edge[i]
    for e in E:
        if(e==i):continue
        sco[i]+=sco[e]
print(*sco[1:])