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

Solution (Python):
import sys
from collections import deque
input = sys.stdin.readline

N, Q = [int(x) for x in input().strip().split()]
res = [0 for _ in range(N)]
tree = [[] for _ in range(N)]
for n in range(N-1):
    a, b = [int(x) for x in input().strip().split()]
    tree[a-1].append(b)

for q in range(Q):
    p, x = [int(x) for x in input().strip().split()]
    res[p-1] += x

q = deque([1])
cq = deque([0])
while q:
    n = q.popleft()
    c = cq.popleft()
    res[n-1] += c
    if len(tree[n-1])!=0:
        for num in tree[n-1]:
            q.append(num)
            cq.append(res[n-1])

print(*res)

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

hen = [[0,0]]*(n-1)
for i in range(n-1) :
    hen[i] = list(map(int,input().split()))

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



hen = sorted(hen, key=lambda x:x[1])
hen = sorted(hen, key=lambda x:x[0])

for i in range(n-1) :
    xlist[hen[i][1]-1] += xlist[hen[i][0]-1]

y = xlist.copy()

c = str(y[0])
for i in range(1,n) :
    c += ' ' + str(y[i])

print(c)

Solution (Python):
import sys
sys.setrecursionlimit(1000000)
def main():
  _map = map
  _input = input
  _int = int
  def calc_results(results, pvalue, i):
    results[i] = pvalue + values[i]
    for j in childrens[i]:
      calc_results(results, results[i], j)
  n, q = _map(_int, _input().split())
  values = [0] * (n + 1)
  results = [0] * (n + 1)
  childrens = [[] for _ in range(n + 1)]
  for i in range(n - 1):
    a, b = _map(_int, _input().split())
    childrens[a].append(b)
  for _ in range(q):
    p, x = _map(_int, _input().split())
    values[p] += x
  calc_results(results, 0, 1)
  print(*[results[i] for i in range(1, n + 1)])
main()

Solution (Python):
n,q = map(int, input().split())
lis = [[] for i in range(n)]
for i in range(n-1):
    a,b = map(int, input().split())
    lis[a-1].append(b)
kotae =[0]*n
c_list = [0]*n
for i in range(q):
    p,x = map(int, input().split())
    c_list[p-1] += x

for i in range(len(lis)):
    kotae[i-1] += c_list[i-1]
    for m in lis[i-1]:
        kotae[m-1] += kotae[i-1]

for i in kotae:
    print(i,end=" ")
print()

Solution (Python):
from collections import deque

R = lambda: map(int, input().split())

n, q = R()
g = [[1]] + [[] for _ in range(n)]
c = [0] * (n + 1)
for _ in range(1, n):
    a, b = R()
    g[a].append(b)
    g[b].append(a)
for _ in range(q):
    p, x = R()
    c[p] += x

vis = [False] * (n + 1)
r = [0] * n
qe = deque([0])
while qe:
    u = qe.popleft()
    for v in g[u]:
        if not vis[v]:
            vis[v] = True
            r[v - 1] = r[u - 1] + c[v]
            qe.append(v)
print(*r)

Solution (Python):
import sys
import collections


def main():
    [n, q] = [int(s) for s in sys.stdin.readline().strip().split()]
    a = [-1] * (n-1)
    b = [-1] * (n-1)
    tree = collections.defaultdict(set)
    for i in range(n-1):
        a[i], b[i] = [int(s) for s in sys.stdin.readline().strip().split()]
        tree[a[i]-1].add(b[i]-1)
        tree[b[i]-1].add(a[i]-1)

    p = [-1] * q
    x = [-1] * q
    adds = [0] * n
    for i in range(q):
        p[i], x[i] = [int(s) for s in sys.stdin.readline().strip().split()]
        adds[p[i]-1] += x[i]

    results = [0] * n
    seen = set()

    
    
    
    
    
    
    
    
    
    
    
    

    for i in range(n):
        results[i] = adds[i]
        for child in tree[i]:
            adds[child] += results[i]
    print(' '.join([str(n) for n in results]))


main()

Solution (Python):
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])

Solution (Python):
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)))

Solution (Python):
N, Q = map(int,input().split())
s = [list(map(int,input().split())) for _ in range(N-1)]
p = [list(map(int,input().split())) for _ in range(Q)]


parent = [0] * (N+1)
count = [0] * (N+1)
for t in s:
    parent[t[1]] = t[0]
for u in p:
    count[u[0]] += u[1]

dp = [0] * (N+1)
for i in range(1,N+1):
    dp[i] = dp[parent[i]] + count[i]

for i in dp[1:]:
    print(i, end=' ')

Solution (Python):
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


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


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


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


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)))

Solution (Python):
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

        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)

Solution (Python):
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:]]))

Solution (Python):
N,Q=map(int,input().split())
arr_ab = [[] for j in range(N)]
for _ in range(N-1):
    a,b=map(int,input().split())
    arr_ab[a-1].extend([b])
arr_px = [0]*N
for _ in range(Q):
    p,x=map(int,input().split())
    arr_px[p-1]+=x

ans = [0]*N

for i in range(N-1):
    for j in arr_ab[i]:
        arr_px[j-1]+=arr_px[i]
print(' '.join(list(map(str, arr_px))))

Solution (Python):
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools, os, pdb
sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-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 _pf(s): return print(s, flush=True)
def perr(s): return print(s, file=sys.stderr)

if 'LOCAL' in os.environ:
    N = 2* 10** 5
    Q = 2 * 10 ** 5
    AB = [[i, i + 1] for i in range(1, N)]
    PX = [[i, 10] for i in range(Q)]
else:
    N, Q = LI()
    AB = []
    PX = []
    for i in range(N-1):
        AB.append(LI())

    for i in range(Q):
        PX.append(LI())


"""
そもそも各頂点の部分木をdictに入れましょうか？
参照するような形で。
2には3
3には4,5
4,5はNoneだと、参照しやすいか？

カウントを若い順にやっていく
"""
AB = sorted(AB, key=lambda x: x[0])
perr('AB')
perr(AB)
d = {}
for p, x in PX:
    if p not in d.keys():
        d[p] = 0
    d[p] += x
for a, b in AB:
    if b not in d.keys():
        d[b] = 0
    if a not in d.keys():
        d[a] = 0
    d[b] += d[a]
for i in range(1, N+1):
    print(d[i], end=' ')

Solution (Python):
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()

Solution (Python):
from collections import deque

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

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

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

point = [0] * n

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

node = [0] * n
node[0] = point[0]

d = deque([0])

while len(d) > 0:
    n_now = d.popleft()

    for n_next in to[n_now]:
        d.append(n_next)
        node[n_next] = node[n_now] + point[n_next]

for i in range(n):
    print(node[i], end="")
    if i != n - 1:
        print(" ", end="")

print("")

Solution (Python):
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)

Solution (Python):
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))

Solution (Python):
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)

Solution (Python):


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))))

Solution (Python):
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)









sen = ""
for i in range(1, N + 1):
  sen += str(res[i])
  if i != N:
    sen += " "
print(sen)

Solution (Python):

import sys
import queue

def solve(N: int, Q: int, a: "List[int]", b: "List[int]", p: "List[int]", x: "List[int]"):
    
    count = [0] * N
    for j in range(Q):
        count[p[j]-1] += x[j]
    
    adj_list = [ [] for i in range(N) ]
    for i in range(N-1):
        u, v = a[i] - 1, b[i] - 1
        adj_list[u] += [v]
        adj_list[v] += [u]
    
    explored = [False] * N
    myqueue = queue.Queue()
    explored[0] = True
    myqueue.put(0)
    while(not myqueue.empty()):
        u = myqueue.get()
        for v in adj_list[u]:
            if explored[v] == False:
                myqueue.put(v)
                explored[v] = True
                count[v] += count[u]
    print(' '.join([str(i) for i in count]))
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    Q = int(next(tokens))  
    a = [int()] * (N-1)  
    b = [int()] * (N-1)  
    for i in range(N-1):
        a[i] = int(next(tokens))
        b[i] = int(next(tokens))
    p = [int()] * (Q)  
    x = [int()] * (Q)  
    for i in range(Q):
        p[i] = int(next(tokens))
        x[i] = int(next(tokens))
    solve(N, Q, a, b, p, x)

if __name__ == '__main__':
    main()

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)



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)]

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

value = [0] * (N+1)
for p,x in PX:
    value[p] += x
    
q = [(1,0)]
while q:
    x,parent = q.pop()
    value[x] += value[parent]
    for y in graph[x]:
        if y == parent:
            continue
        q.append((y,x))

answer = ' '.join(map(str,value[1:]))
print(answer)

Solution (Python):
import sys
sys.setrecursionlimit(10**6)


def main():
    input = sys.stdin.readline
    n, q = map(int, input().split())
    e = [list(map(int, input().split())) for _ in range(n-1)]
    p = [list(map(int, input().split())) for _ in range(q)]

    e2 = [{} for _ in range(n)]
    for ee in e:
        a, b = ee
        e2[a-1][b-1] = 1
        e2[b-1][a-1] = 1

    counters = [0 for _ in range(n)]
    for pp in p:
        counters[pp[0]-1] += pp[1]

    def dfs(x, p_sum):
        counters[x] += p_sum
        for y in e2[x]:
            del e2[y][x]
            dfs(y, counters[x])

    dfs(0, 0)
    print(*counters)


main()

Solution (Python):
I=lambda:map(int,input().split())
n,q=I()
e=[[]for _ in range(n)]
d=[0]*n
for _ in range(n-1):
    a,b=I()
    e[a-1]+=b-1,
    e[b-1]+=a-1,
for _ in range(q):
    p,x=I()
    d[p-1]+=x
f=[1]+[0]*n
q=[0]
while q:
    v=q.pop()
    for w in e[v]:
        if f[w]:continue
        f[w]=1
        d[w]+=d[v]
        q+=w,
print(*d)

Solution (Python):
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)))

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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)))

Solution (Python):
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)
            

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

Solution (Python):
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()

Solution (Python):
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)))))

Solution (Python):
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)))

Solution (Python):

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

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() 
for _ in range(Q):
    ope = tuple(map(int, input().split()))
    score[ope[0]] += ope[1] 
for i in range(N-1):
    score[edge[i][1]] += score[edge[i][0]]
score.remove(score[0])
print(*score)

Solution (Python):
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))))

Solution (Python):
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]))

Solution (Python):


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)

Solution (Python):
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)

Solution (Python):
N, Q = map(int,input().split())
G = [[] for i in range(N+ 1)]
ANS = [0] * (N + 1)
for _ in range(N - 1):
    a , b = map(int,input().split())
    G[a].append(b)
for _ in range(Q):
    p, x =map(int,input().split())
    ANS[p] += x
from collections import deque
que=deque([])
que.append(1)
while que:
    node = que.pop()
    ans = ANS[node]
    for child in G[node]:
        ANS[child] += ans
        que.append(child)
for i in range(1, N + 1):
    print(ANS[i])

Solution (Python):
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

    
    

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

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

Solution (Python):
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:]]))

Solution (Python):
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=" ")

Solution (Python):
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)))

Solution (Python):
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()

Solution (Python):
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  
        dfs(chl, v+x[chl], n)
    return

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

Solution (Python):
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))

Solution (Python):


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, 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)]

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

Solution (Python):
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)

Solution (Python):
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()

Solution (Python):
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()