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):
def main(sample_file = ''):

    """ convenient functions
    
    
    
    
    
    """

    """convenient decorator
    
    
        
        
        
        
        
        
        
        
        
        
    """
    
    
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product 
    
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  
        b, e = 2, 0  
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict 
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest 
    from copy import deepcopy, copy 
    import operator
    from operator import itemgetter 
    
    
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd 
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)
    def make_divisors(n, reversed=False):
        """create list of divisors
        
        Args:
            number (int): number from which list of divisors is created
            reversed (bool, optional): ascending order if False. Defaults to False.
        
        Returns:
            list: list of divisors
        """
        divisors = set()
        for i in range(1, int(n**0.5)+1):
            if n % i == 0:
                divisors.add(i)
                divisors.add(n//i)
        return sorted(list(divisors),reverse=reversed)
    
    
    
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) 
    def modinv(a, p = MOD):
        
        
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        
        
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    class UnionFindTree:
        """union find tree class
        TODO: fix this description...
        how to use (example):
        >>  uf = UnionFindTree(N) 
        >>  if uf.find_root(a) == uf.find_root(b):
        >>      do something
        >>  else:
        >>      do something
        >>      uf.unite(a, b)
        """
        def __init__(self, N):
            self.root = [-1] * (N+1)
            self.rank   = [0]  * (N+1)
            self.connected_num = [1] * (N+1)
    
        def find_root(self,x):
            root = self.root
            while root[x] != -1:
                x = root[x]
            return x
    
        def unite(self,x,y):
            root = self.root
            rank = self.rank
            connected_num = self.connected_num
            find_root = self.find_root
    
            rx = find_root(x)
            ry = find_root(y)
            if rx != ry:
                if rank[rx] < rank[ry]:
                    root[rx] = ry
                    rx,ry = ry,rx
                else:
                    if rank[rx] == rank[ry]:
                        rank[rx] += 1
                    root[ry] = rx       
                connected_num[rx] += connected_num[ry]

    
    
    
    
    

    def BellmanFord(N, M, ABC, vertex_start, vertex_end, value_if_inf = -1, find_shortest = False):
        """to calculate furthest or shortest length between vertex_start and vertex_end using BellmanFord algorithm
        
        Args:
            N (int): number of vertices
            M (int): number of edges
            ABC (list): [(ai, bi, ci) for _ in range(N)] where i-th edge is directed from vertex ai to vertex bi and the length is ci 
            vertex_start (int): start vertex. usually use 0.
            vertex_end (int): end vertex. usually use N-1.
            value_if_inf (int or string as you like, optional): value you want when the furthest (or shortest) distance is infinite (or -infinite). Defaults to -1.
            find_shortest (bool, optional): choose False to find furthest path. Defaults to False.
        
        Returns:
            int or string: normally int (but can be str if you set value_if_inf to str)
            
        Example:
                N, M, P = R()
                ABC = [R() for _ in range(M)]
                ABC = [(a-1, b-1, c-P) for a, b, c in ABC]
                print(BellmanFord(N, M, ABC, 0, N-1, value_if_inf = 'inf'))

        """

        def make_reachable_list(N, M, ABC, vertex_start, vertex_end):
            reachable_to_direct = defaultdict(list)
            reachable_from_direct = defaultdict(list)
            reachable_from_start = [False] * N
            reachable_to_end = [False] * N
            reachable_from_start[vertex_start] = True
            reachable_to_end[vertex_end] = True
            reachable_from_both_sides = [False] * N
            dfs_from_start = []
            dfs_to_end = []
            for a, b, c in ABC:
                reachable_to_direct[a].append(b)
                reachable_from_direct[b].append(a)
                if a == vertex_start:
                    dfs_from_start.append(b)
                    reachable_from_start[b] = True
                if b == vertex_end:
                    dfs_to_end.append(a)
                    reachable_to_end[a] = True
            while dfs_from_start:
                v = dfs_from_start.pop()
                for i in reachable_to_direct[v]:
                    if not reachable_from_start[i]:
                        reachable_from_start[i] = True
                        dfs_from_start.append(i)
            while dfs_to_end:
                v = dfs_to_end.pop()
                for i in reachable_from_direct[v]:
                    if not reachable_to_end[i]:
                        reachable_to_end[i] = True
                        dfs_to_end.append(i)
            for i in range(N):
                reachable_from_both_sides[i] = reachable_from_start[i] and reachable_to_end[i]
            return reachable_from_both_sides
        
        reachable_from_both_sides = make_reachable_list(N, M, ABC, vertex_start, vertex_end)
        
        if find_shortest:
            dist = [INF for i in range(N)]
        else:
            dist = [-INF for i in range(N)]
        
        dist[vertex_start] = 0
        for i in range(N):
            updated = False
            for a, b, c in ABC:
                if not reachable_from_both_sides[a]:
                    continue
                elif find_shortest:
                    update_condition = dist[a] + c < dist[b]
                else:
                    update_condition = dist[a] + c > dist[b]
                if dist[a] != INF and update_condition:
                    dist[b] = dist[a] + c
                    updated = True
                    if i == N-1:
                        return value_if_inf
            if not updated:
                break
        return dist[vertex_end]

    """ initialize variables and set inputs
    
        
        
    
        
        
        
        
        
        
        
    
        
        
        
        
    
        
        
    """

    
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    R = lambda: list(map(int, r().split()))
    Rmap = lambda: map(int, r().split())
    Rfloat = lambda: list(map(float, r().split()))
    Rtuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    
    
    
    
    
    
    
    """

    
    if sample_file:
        sys.stdin = open(sample_file)
        
    
    

    N, Q = R()
    AB = [R() for _ in range(N-1)]
    PX = [R() for _ in range(Q)]
    
    Tree = [[] for _ in range(N)]
    Val = [0] * N
    for p, x in PX:
        p = p - 1
        Val[p] += x
    
    for a, b in AB:
        a, b = a-1, b-1
        Tree[a].append(b)
    
    task = []
    task.append(0)
    while task:
        i = task.pop()
        tmpval = Val[i]
        task.extend(Tree[i])
        for j in Tree[i]:
            Val[j] += Val[i]
    print(*Val)

    
    
    

    
    
    

    """memo: how to use defaultdict of list
    
    Dic = defaultdict(list)
    
    Dic[x].append(y)
    
    for k, v in Dic.items():
    """
    
    """memo: how to solve binary problems
    
    >>> a = 5
    >>> bin_str_a = format(a, '
    >>> print(bin_str_a)
    0b0101 
    """
    
    """memo: how to solve the problem
    creating simple test/answer
    greed
    simple dp
    graph
    """

if __name__ == '__main__':
    main()

Solution (Python):
n,q=map(int,input().split())
to = [[]for _ in range(n)]
for i in range(n-1):
    a,b=map(int,input().split())
    to[a-1].append(b-1)
cost=[0]*n

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

from collections import deque
que = deque([0])

while(que):
    f = que.popleft()
    for t in to[f]:
        que.append(t)
        cost[t]+=cost[f]

print(" ".join([str(x)for x in cost]))

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


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)

Solution (Python):
N,Q = map(int,input().split())
point = [[] for x in range(N)]
plus = [0]*N
for _ in range(N-1):
    a,b = map(int,input().split())
    a -= 1
    b -= 1
    point[a].append(b)

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

ans = [0]*N
dfs = [(0,0)]
while len(dfs):
    n,p = dfs.pop()
    p += plus[n]
    ans[n] = p
    for be in point[n]:
        dfs.append((be,p))

for a in ans:
    print(a,end=' ')
print()

Solution (Python):
def main():
    from collections import defaultdict
    from collections import deque
    import sys
    input = sys.stdin.readline
    dd = defaultdict(list)
    pq = defaultdict(int)

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

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

    for _ in range(Q):
        p,q = map(int, input().split())
        pq[p] += q
    
    answer = [0]*N
    queue = deque()
    queue.append(1)

    while queue != deque():
        tmp = queue.popleft()
        answer[tmp-1] += pq[tmp]
        for i in dd[tmp]:
            queue.append(i)
            answer[i-1] += answer[tmp-1]
            
    print(*answer)

if __name__ == '__main__':
    main()

Solution (Python):
import sys
sys.setrecursionlimit(1000000)


input = raw_input
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():
    def __init__(self, v):
        self.parent = None
        self.v = v
        self.x = 0
        self.memo = None

    def add(self, x):
        self.x += x

    def calc(self):
        if self.v == 1:
            return self.x
        if self.memo is not None:
            return self.memo

        tmp = self.parent.calc()
        self.memo = tmp + self.x
        return self.memo



trees = {i: Tree(i) for i in range(1, N + 1)}

for a,b in ab:
    trees[b].parent = trees[a]

for p,x in px:
    trees[p].add(x)


print(" ".join(map(str,[trees[i].calc() for i in range(1,N+1)])))

Solution (Python):
def main():
    from collections import defaultdict
    from collections import deque
    import sys
    input = sys.stdin.readline
    dd = defaultdict(list)
    pq = defaultdict(int)

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

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

    for _ in range(Q):
        p,q = map(int, input().split())
        pq[p] += q
    
    answer = [0]*N
    queue = deque()
    queue.append(1)

    while queue != deque():
        tmp = queue.popleft()
        answer[tmp-1] += pq[tmp]
        for i in dd[tmp]:
            queue.append(i)
            answer[i-1] += answer[tmp-1]
            
    print(*answer)

if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque

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

L = [[] for i in range(N)]
for i in range(N-1) :
    u,v = map(int,input().split())
    u -= 1
    v -= 1
    L[u].append(v)
    L[v].append(u)

par = [-1]*N

cnt = [0]*N

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

q = deque([0])
while len(q) :
    u = q.popleft()
    for v in L[u] :
        if v == par[u] :
            continue
        par[v] = u
        cnt[v] += cnt[u]
        q.append(v)


"""
for i in range(Q) :
    p,x = map(int,input().split())
    p -= 1
    q = deque([p])
    while len(q) :
        u = q.popleft()
        cnt[u] += x
        for v in L[u] :
            if v != par[u] :
                q.append(v)
"""
print(*cnt)

Solution (Python):
import collections
n, q = map(int, input().split())
d = collections.defaultdict(list)
score = [0 for i in range(n)]
for _ in range(n-1):
    a,b = map(int, input().split())
    d[a].append(b)
for _ in range(q):
    p, x = map(int, input().split())
    score[p-1] += x
for node in range(1, n+1):
    child = d[node]
    for c in child:
        score[c-1] += score[node-1]
print(" ".join(map(str, score)))

Solution (Python):
N,Q=map(int,input().split())
L=[[]for i in range(N+1)]
for i in range(N-1):
    a,b=map(int,input().split())
    L[a].append(b)
    L[b].append(a)
    
S=[0 for i in range(N+1)]
for i in range(Q):
    p,x=map(int,input().split())
    S[p]+=x
    
ANS=[-1 for i in range(N+1)]
ANS[1]=S[1]
l=[]
for i in L[1]:
    l.append([i,1,S[1]])
    
for i in range(N-1):
    X=l[i][0]
    Y=l[i][1]
    Z=l[i][2]
    ANS[X]=Z+S[X]
    for j in L[X]:
        if ANS[j]<0:
            l.append([j,X,ANS[X]])
print(*ANS[1:])

Solution (Python):
n,q=map(int,input().split())
edge=[[] for i in range(n+1)]
for i in range(n-1):
    a,b=map(int,input().split())
    edge[a].append(b)
    edge[b].append(a)
px=[0 for i in range(n+1)]
for i in range(q):
    p,x=map(int,input().split())
    px[p]+=x
s=[1]
c=[1]*(n+1)
c[1]=0
while s:
    t=s.pop()
    for i in edge[t]:
        if c[i]:
            c[i]=0
            px[i]+=px[t]
            s.append(i)
print(" ".join(map(str,px[1:])))

Solution (Python):
N,Q = map(int,input().split())
AB = [list(map(int,input().split())) for _ in [0]*(N-1)]
PX = [list(map(int,input().split())) for _ in [0]*Q]

E = [[] for _ in [0]*N]
for a,b in AB:
    a-=1
    b-=1
    E[a].append(b)
    E[b].append(a)

P = [-1]*N
P[0] = 0
q = [0]
while q:
    i = q.pop()
    for j in E[i]:
        if P[j]!=-1: continue
        P[j] = i
        q.append(j)
P[0] = -1

V = [0]*N
for p,x in PX:
    p-=1
    V[p] += x

q = [0]
done = [False]*N
while q:
    i = q.pop()
    done[i] = True
    for j in E[i]:
        if done[j] : continue
        V[j] += V[i]
        q.append(j)

print(*V)

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


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

q = [0]
while q:
    p = q.pop()
    for c in g[p]:
        ans[c] += ans[p]
        q.append(c)

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

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

dw = [[] for i in range(n+1)]
pt = [0 for i in range(n+1)]

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

for i in range(q):
    a,b = list(map(int, input().split()))
    pt[a] += b

slist = [1]

while(True):
    nlist = []
    for i in range(len(slist)):
        nowlist = dw[slist[i]]
        for j in range(len(nowlist)):
            pt[nowlist[j]] += pt[slist[i]]
            nlist.append(nowlist[j])
    
    if(len(nlist)==0):
        break
    slist = nlist
pt = ' '.join(map(str, pt[1:]))
print(pt)

Solution (Python):

import sys
from collections import deque
INF = float("inf")


class Graph(object):
    def __init__(self, N):
        self.N = N
        self.E = [[] for _ in range(N)]

    def add_edge(self, edge):
        """辺を加える。edgeは(始点, 終点、重み)からなるリスト
        重みがなければ、重み1とする。
        """
        if len(edge) == 2:
            edge.append(1)
        elif len(edge) != 3:
            print("error in add_edge")

        s, t, w = edge
        self.E[s].append([t, w])
        self.E[t].append([s, w])


def solve(N: int, Q: int, a: "List[int]", b: "List[int]", p: "List[int]", x: "List[int]"):
    g = Graph(N)
    for aa, bb in zip(a, b):
        g.add_edge([aa-1, bb-1, 1])

    P = [0]*N
    for pp, xx in zip(p, x):
        P[pp-1] += xx

    visit = deque()
    visit.append((0, None))
    counter = [0]*N
    while len(visit) > 0:
        
        curr, par = visit.popleft()
        counter[curr] += P[curr]
        for t, w in g.E[curr]:
            if t == par:
                continue
            visit.append((t, curr))
            counter[t] += counter[curr]
    print(*counter)
    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
sys.setrecursionlimit(10000000)

def main():
    N,Q = map(int,sys.stdin.readline().split())
    e = [ [ ] for i in range(N)]
    for i in range(N-1):
        a,b = map(int,sys.stdin.readline().split())
        e[a-1].append(b-1)

    from collections import defaultdict
    d = defaultdict(int)
    for i in range(Q):
        p,x = map(int,sys.stdin.readline().split())
        d[p-1] += x

    ansl = [0 for i in range(N)]

    def dfs(x,c):
        c += d[x]
        ansl[x] = c
        for v in e[x]:
            dfs(v,c)

    dfs(0,0)
    print(" ".join(map(str,ansl)))
if __name__ == '__main__':
    main()

Solution (Python):
import sys
sys.setrecursionlimit(200010)

def main():
    input = sys.stdin.readline
    N, Q = map(int,input().split())
    G = [[] for k in range(N+1)]
    for k in range(N-1):
        a, b = map(int,input().split())
        G[a].append(b)
    kyori = [0 for k in range(N+1)]
    for k in range(Q):
        p, x = map(int,input().split())
        kyori[p] -= x
    def dfs(now, dist):
        for tsugi in G[now]:
            if kyori[tsugi] <= 0:
                kyori[tsugi] = -kyori[tsugi]
                kyori[tsugi] += dist
                dfs(tsugi, kyori[tsugi])
    kyori[1] = -kyori[1]
    dfs(1,kyori[1])
    print(*kyori[1:], sep = " ")

if __name__ == '__main__':
    main()

Solution (Python):

import sys, math, fractions, itertools, collections, copy, heapq


def solve(N: int, Q: int, a: "List[int]", b: "List[int]", p: "List[int]", x: "List[int]"):
    G = [[] for _ in range(N)]
    for i in range(N-1):
        G[a[i]-1].append(b[i]-1)
        G[b[i]-1].append(a[i]-1)
    w = [0] * N
    for i in range(Q):
        w[p[i]-1] += x[i]
    stack = [0]
    visited = [0] * N
    while len(stack) > 0:
        t = stack.pop()
        visited[t] = 1
        adj = G[t]
        for a in adj:
            if visited[a] == 0:
                stack.append(a)
                w[a] += w[t]
    print(' '.join([str(ww) for ww in w]))
    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):
n,q = map(int,input().split())
lis = [0 for i in range(n)]
li = [0 for i in range(n)]
tree = [0 for i in range(n)]
for i in range(n-1):
    a,b = map(int,input().split())
    tree[b-1] = a-1
for i in range(q):
    c,d = map(int,input().split())
    li[c-1] += d
lis[0] = li[0]
for i in range(1,n):
    lis[i] = lis[tree[i]]+li[i]
for i in range(n):
    lis[i] = str(lis[i])
print(" ".join(lis))

Solution (Python):
def solve():
    import sys
    sys.setrecursionlimit(10**9)
    input = sys.stdin.readline

    N, Q = map(int, input().split())
    adjL = [[] for _ in range(N)]
    for _ in range(N-1):
        A, B = map(int, input().split())
        A, B = A-1, B-1
        adjL[A].append(B)
        adjL[B].append(A)

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

    useds = [False] * N
    def dfs(vNow, x):
        useds[vNow] = True
        anss[vNow] += x
        ans = anss[vNow]
        for v2 in adjL[vNow]:
            if not useds[v2]:
                dfs(v2, ans)

    dfs(0, 0)

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

solve()

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

import sys
sys.setrecursionlimit(500000)
N, Q = map(int, input().split())
E = [[] for _ in range(N+1)]
for _ in range(N-1):
    a, b = map(int, input().split())
    E[a].append(b)
    E[b].append(a)
C = [0] * (N+1)
for _ in range(Q):
    p, x = map(int, input().split())
    C[p] += x
Ans = [0] * (N+1)
def dfs(v, p, a):
    a += C[v]
    Ans[v] = a
    for u in E[v]:
        if u!=p:
            dfs(u, v, a)
dfs(1, 0, 0)
print(" ".join(map(str, Ans[1:])))

Solution (Python):
N, Q = map(int, input().split())
tree = [[] for i in range(N+1)]
counter = [0] * (N+1)

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

for i in range(Q):
    p, x = map(int, input().split())
    counter[p] += x
for i in range(1, N+1):
    for pn in tree[i]:
        counter[i] += counter[pn]

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

Solution (Python):
N, Q = map(int, input().split())
T = [[] for i in range(N)]
for i in range(N - 1):
    a, b = map(int, input().split())
    a, b = a - 1, b - 1
    T[a].append(b)
    T[b].append(a)

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

ans = [0] * N

stack = [[0, Point[0]]]
visited = [False] * N
while stack:
    n, p = stack.pop()
    visited[n] = True
    ans[n] = p
    for to in T[n]:
        if visited[to]:
            continue
        stack.append([to, p + Point[to]])

print(*ans, sep=' ')

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

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

edge_dic = defaultdict(lambda: [])

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

ans_array = [0] * N

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


node_deque = deque()
used_array = [-1] * N
node_deque.append(0)
used_array[0] = 1

while len(node_deque):
    node = node_deque.popleft()
    for n in edge_dic[node]:
        if used_array[n] == 1:
            continue
        ans_array[n] += ans_array[node]
        used_array[n] = 1
        node_deque.append(n)

ans_str = map(str,ans_array)
print(" ".join(ans_str))

Solution (Python):
import sys

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

child = [[] for _ in range(n+1)]
for i in range(n-1):
    a, b = map(int, sys.stdin.readline().split())
    child[a].append(b)

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

wait = [1]

while True:
    target = wait.pop()
    for nex in child[target]:
        score[nex] += score[target]
        wait.append(nex)
    if len(wait) == 0:
        break

score.pop(0)

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

Solution (Python):
from collections import defaultdict
import sys
sys.setrecursionlimit(10 ** 6)
input=sys.stdin.readline

def main():
    def dfs(i,oi=-1,s=0):
        ans[i]=s+d[i]
        for ki in to[i]:
            if ki==oi:continue
            dfs(ki,i,s+d[i])

    n,q=map(int, input().split())
    to=defaultdict(list)
    d=[0]*n
    ans=[0]*n
    for _ in range(n-1):
        a,b=map(int, input().split())
        a-=1
        b-=1
        to[a].append(b)
        to[b].append(a)
    for _ in range(q):
        p, x = map(int, input().split())
        d[p-1]+=x
    dfs(0)
    print(*ans)

main()

Solution (Python):
import collections

n,q=map(int,input().split())
cnt=[0]*(n+1)
g=[[] for _ in range(n+1)]
for _ in range(n-1):
  a,b=map(int,input().split())
  g[a].append(b)
  g[b].append(a)
for _ in range(q):
  v,val=map(int,input().split())
  cnt[v]+=val
q=collections.deque()
q.append(1)
checked=[0]*(n+1)
while q:
  v=q.pop()
  checked[v]=1
  for u in g[v]:
    if checked[u]==1:
      continue
    cnt[u]+=cnt[v]
    q.append(u)
print(*cnt[1:])