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: Wrong Answer

Solution code:
import sys

stdin = sys.stdin
na = lambda: map(int, stdin.readline().split())

def main():
  N, Q = na()

  ab = []
  for _ in range(N-1):
    a, b = na()
    ab.append([a, b])

  counter = [0] * (N+1)
  for _ in range(Q):
    p, x = na()
    counter[p] += x
  for i in range(N - 1):
    counter[ab[i][1]] += counter[ab[i][0]]
  print(*counter[1:])

if __name__ == "__main__":
  main()

Submission status: Wrong Answer

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

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

n2w = [0]*(N+1)
for _ in range(Q):
  tmp = list(map(int,input().split()))
  n2w[tmp[0]] += tmp[1]

for a,b in edge:
  n2w[b] += n2w[a]

print(*n2w[1:])

Submission status: Wrong Answer

Solution code:
input_line = list(map(int,input().split()))
tree_info = []
for i in range(input_line[0]-1):
    info = list(input().split())
    tree_info.append(info)
counter = [0] * input_line[0]
for i in range(input_line[1]):
    count_info = list(map(int, input().split()))
    counter[count_info[0]-1] += count_info[1]
for i in range(1,len(counter)):
    counter[i] += counter[i-1]
print(" ".join(list(map(str,counter))))

Submission status: Wrong Answer

Solution code:
num=input().split( )
num=[int(n) for n in num]
N=num[0]
Q=num[1]

a=[]
b=[]
for i in range(N-1):
    num=input().split( )
    num=[int(n) for n in num]
    a.append(num[0])
    b.append(num[1])

counter=[0]*N
def addCounter(p, q):
    index=[j for j, k in enumerate(a) if k == p]
    for j in index:
        addCounter(b[j], q)
    counter[p-1]=counter[p-1] +q

for i in range(Q):
    num=input().split( )
    num=[int(n) for n in num]
    addCounter(num[0], num[1])

print(counter)

Submission status: Wrong Answer

Solution code:

NQ = input().split(' ')
N = int(NQ[0])
Q = int(NQ[1])
candidate_list = []
tree_list = [[]] * N
#Make tree dict
for i in range(N-1):
    ab = input().split(' ')
    a = int(ab[0])
    b = int(ab[1])
    candidate_list.append((a,b))
candidate_list.reverse()
for candidate in candidate_list:
    a = candidate[0]
    b = candidate[1]
    tree_list[a-1] = tree_list[a-1] + tree_list[b-1]
    tree_list[a-1].append(b)
out_put_list = [0] * N
for _ in range(Q):
    px = input().split(' ')
    p = int(px[0])
    x = int(px[1])
    out_put_list[p-1] += x
    for idx in tree_list[p-1]:
        out_put_list[idx-1] += x
    
print(' '.join(map(str,out_put_list)))

Submission status: Wrong Answer

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

parent={1:[1]}

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

top_counter=[0 for i in range(n)]

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

# print(top_counter)

counter=[0 for i in range(n)]
for i in range(n):
    check=set(parent[i+1])
    print(check)
    for j in check:
        counter[i]+=top_counter[j-1]

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

Submission status: Wrong Answer

Solution code:
N, Q = map(int, input().split())
value = [0]*(N+1)
a_list = []
b_list = []
for i in range(N-1):
  a, b = map(int, input().split())
  a_list.append(a)
  b_list.append(b)
for i in range(Q):
  p, q = map(int, input().split())
  value[p] += q
for a, b in zip(a_list, b_list):
  value[b] += value[a]
print(' '.join(map(str, value[1:])))

Submission status: Wrong Answer

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)]
 
neigh = {}
 
scores = [0] * n
 
for i in range(q) :
    scores[px[i][0] - 1] += px[i][1]
print(*scores) 
for i in range(n - 1) :
    neigh.setdefault(ab[i][0], []).append(ab[i][1])
#print(neigh)

for k in sorted(neigh.keys()):
    for e in neigh[k]:
        scores[e-1]+=scores[k-1]
 
print(*scores)

Submission status: Wrong Answer

Solution code:
n, q = map(int, input().split())
ab = [list(map(int, input().split())) for i in range(n-1)]
px = [list(map(int, input().split())) for i in range(q)]
p = [0 for i in range(n)]
for i in px:
  p[i[0] - 1] += i[1]
s = ""
for i in ab:
  p[i[1]-1] += p[i[0]-1]
print(" ".join(map(str, p)))

Submission status: Wrong Answer

Solution code:
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n, q = na()
li = [0 for i in range(n)]
ab = []
for i in range(n-1):
    ab.append(na())
for i in range(q):
    p, x = na()
    li[p-1] += x
for a, b in ab:
    li[b-1] += li[a-1]
print(*li)

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
from functools import lru_cache

def main():
    n, q = map(int, input().split())
    ab = [[],[]]
    
    for i in range(n-1):
        na,nb = map(int, input().split())
        ab[0].append(na)
        ab[1].append(nb)

    px = [[],[]]
    for i in range(q):
        np,nx = map(int, input().split())        
        px[0].append(np)
        px[1].append(nx)
    
    # print(n,q,ab,px)
    count = [0 for i in range(n)]

    oya_list = [0 for i in range(n)]
    for i in range(len(ab[1])):
        oya_list[ab[1][i]-1] = ab[0][i]
    
    for i in range(len(px[1])):
        count[px[0][i]-1] += px[1][i]
    
    print(count)
    
    for i in range(1,n):

        count[i] += count[oya_list[i]-1]
    
    print(' '.join(map(str,count)))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

parent={1:[1]}

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

top_counter=[0 for i in range(n)]

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

# print(top_counter)

counter=[0 for i in range(n)]
for i in range(n):
    check=set(parent[i+1])
    print(check)
    for j in check:
        counter[i]+=top_counter[j-1]

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

Submission status: Wrong Answer

Solution code:
N, Q = map(int,input().split())
i = 1
AB = list()
while i <= N-1:
    AB.append(list(map(int,input().split())))
    i += 1
print(AB)
i = 1
PX = list()
while i <= Q:
    PX.append(list(map(int,input().split())))
    i += 1
    print(PX)

print(PX)

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

level = 0
tree = [[1]]
while AB:
    i = 0
    tree.append([])
    delis = list()
    for a, b in AB:
        if a in tree[level]:
            tree[level+1].append(b)
            delis.append(i)
        if b in tree[level]:
            tree[level+1].append(a)
            delis.append(i)
        i += 1
    print(AB)
    print(tree)
    level += 1
    for j in delis:
        AB[j] = 0
        print(j)
    AB = [i for i in AB if i != 0]
print(tree)

for p, x in PX:
    i = 0
    for t in tree:
        if p in t:
            break
        i+=1

    V[p-1] += x
    i += 1
    while i < len(tree):
        t = tree[i]
        for n in t:
            V[n-1] += x
        i+=1
print(' '.join(map(str,V)))

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
from functools import lru_cache

def main():
    n, q = map(int, input().split())
    ab = [[],[]]
    
    for i in range(n-1):
        na,nb = map(int, input().split())
        ab[0].append(na)
        ab[1].append(nb)

    px = [[],[]]
    for i in range(q):
        np,nx = map(int, input().split())        
        px[0].append(np)
        px[1].append(nx)
    
    # print(n,q,ab,px)
    count = [0 for i in range(n)]

    oya_list = [0 for i in range(n)]
    for i in range(len(ab[1])):
        oya_list[ab[1][i]-1] += ab[0][i]
    
    for i in range(len(px[1])):
        count[px[0][i]-1] = px[1][i]
    
    print(count)
    
    for i in range(1,n):

        count[i] += count[oya_list[i]-1]
    
    print(' '.join(map(str,count)))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import collections

N, Q = [int(i) for i in input().split()]
parents = [None] * (N + 1)
result = [0] * (N + 1)

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

for _ in range(Q):
    p, x = [int(i) for i in input().split()]
    result[p] += x

for i in range(1, N + 1):
    if parents[i] is not None:
        result[i] += result[parents[i]]

print(result[1:N + 1])

Submission status: Wrong Answer

Solution code:
import collections

N, Q = [int(i) for i in input().split()]
result = [0] * (N + 1)

for _ in range(N - 1):
    input()

for _ in range(Q):
    p, x = [int(i) for i in input().split()]
    result[p] += x

for i in range(1, N + 1):
    result[i] += result[i - 1]

print(result[1:N + 1])

Submission status: Wrong Answer

Solution code:
import numpy as np

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

edge = []
for _ in range(N-1):
    edge.append(list(map(int, input().split())))
#edge = sorted(edge)
wgt = []
for _ in range(Q):
  wgt.append(list(map(int,input().split())))

  
n2w = {}
for i in range(1,N+1):
  n2w[i] = 0
for p,x in wgt:
  n2w[p] += x

for a,b in edge:
  n2w[b] += n2w[a]

ret = ''
for s in n2w.values():
  ret += str(s) + ' '
print(ret)

Submission status: Wrong Answer

Solution code:
N, Q = map(int,input().split())
i = 1
AB = list()
while i <= N-1:
    AB.append(list(map(int,input().split())))
    i += 1
print(AB)
i = 1
PX = list()
while i <= Q:
    PX.append(list(map(int,input().split())))
    i += 1
    print(PX)

print(PX)

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

level = 0
tree = [[1]]
while AB:
    i = 0
    tree.append([])
    delis = list()
    for a, b in AB:
        if a in tree[level]:
            tree[level+1].append(b)
            delis.append(i)
        if b in tree[level]:
            tree[level+1].append(a)
            delis.append(i)
        i += 1
    print(AB)
    print(tree)
    level += 1
    for j in delis:
        AB[j] = 0
        print(j)
    AB = [i for i in AB if i != 0]
print(tree)

for p, x in PX:
    i = 0
    for t in tree:
        if p in t:
            break
        i+=1

    V[p-1] += x
    i += 1
    while i < len(tree):
        t = tree[i]
        for n in t:
            V[n-1] += x
        i+=1
print(' '.join(map(str,V)))


# print(T)
#
# j = 0
# for p,x in PX:
#     if p in AB[j]:
#         T[p-1] += x

Submission status: Wrong Answer

Solution code:
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n, q = na()
li = [0 for i in range(n)]
ab = []
for i in range(n-1):
    a, b = na()
    a -= 1
    b -= 1
    ab.append([a, b])
for i in range(q):
    p, x = na()
    li[p-1] += x
for a, b in ab:
    li[b] += li[a]
print(*li)

Submission status: Wrong Answer

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

edge = []
for _ in range(N-1):
    edge.append(list(map(int, input().split())))
#edge = sorted(edge)
wgt = []
for _ in range(Q):
  wgt.append(list(map(int,input().split())))

  
n2w = {}
for i in range(1,N+1):
  n2w[i] = 0
for p,x in wgt:
  n2w[p] = x

for a,b in edge:
  n2w[b] += n2w[a]

ret = ''
for s in n2w.values():
  ret += str(s) + ' '
print(ret)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict as dd
class Tree:
   def __init__(self, n):
        self.n = n
        self.tree = dd(list)
        self.value = dd(int)
    
   def addNode(self, u, v):
        self.tree[u].append(v)
    
   def update(self, u, n):
       self.value[u] += n
   
   def query(self,root):
       try:
         for node in self.tree[root]:
           self.value[node] += self.value[root]
           self.query(node)
       except:
            pass
   
   def ans(self):
       self.query(1)
       for i in xrange(1,self.n+1):
           print self.value[i],
       print ""

f = lambda : map(int, raw_input().split())

n, q = f()
tree = Tree(n)
for i in xrange(n - 1):
   tree.addNode(*f())
   
for i in xrange(q):
   tree.update(*f())

tree.ans()

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
from functools import lru_cache

def main():
    n, q = map(int, input().split())
    ab = [[],[]]
    
    for i in range(n-1):
        na,nb = map(int, input().split())
        ab[0].append(na)
        ab[1].append(nb)

    px = [[],[]]
    for i in range(q):
        np,nx = map(int, input().split())        
        px[0].append(np)
        px[1].append(nx)
    
    # print(n,q,ab,px)
    count = [0 for i in range(n)]

    oya_list = [0 for i in range(n)]
    for i in range(len(ab[1])):
        oya_list[ab[1][i]-1] = ab[0][i]
    
    for i in range(len(px[1])):
        count[px[0][i]-1] = px[1][i]

    
    for i in range(1,n):

        count[i] += count[oya_list[i]-1]
    
    print(' '.join(map(str,count)))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n, q = map(int, input().split())
abab = [list(map(int, input().split())) for _ in range(n-1)]
pxpx = [list(map(int, input().split())) for _ in range(q)]

ans = [0 for _ in range(n)]
for p, x in pxpx :
    ans[p-1] += x
for a, b in abab :
    ans[b-1] += ans[a-1]
print(*ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
N,Q=map(int,input().split())
ab=[]
px=[]
count=np.zeros(N)
for i in range(N-1):
    ab.append(list(map(int, input().split())))
for i in range(Q):
    px.append(list(map(int, input().split())))

for i in range(Q):
    temp=[]
    count[px[i][0]-1] +=px[i][1]
    for j in range(N-1):
        if ab[j][0] == px[i][0] or ab[j][0] in temp:
            temp.append(ab[j][1])
    for j in range(len(temp)):
        count[temp[j]-1] +=px[i][1]

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict as dd
class Tree:
   def __init__(self, n):
        self.n = n
        self.tree = dd(list)
        self.value = dd(int)
    
   def addNode(self, u, v):
        self.tree[u].append(v)
    
   def update(self, u, n):
       self.value[u] += n
   
   def query(self,root):
       for node in self.tree[root]:
           self.value[node] += self.value[root]
           self.query(node)
   
   def ans(self):
       #self.query(1)
       for i in xrange(1,self.n+1):
           print self.value[i],
       print ""

f = lambda : map(int, raw_input().split())

n, q = f()
tree = Tree(n)
for i in xrange(n - 1):
   tree.addNode(*f())
   
for i in xrange(q):
   tree.update(*f())

tree.ans()

Submission status: Wrong Answer

Solution code:
import sys


N, Q = map(int, sys.stdin.readline().rstrip().split())

nodes = [0 for _ in range(N)]

branches = []
for j in range(N - 1):
    parent, child = map(int, sys.stdin.readline().rstrip().split())
    branches.append([parent - 1, child - 1])

for _ in range(Q):
    parent, number = map(int, sys.stdin.readline().rstrip().split())
    nodes[parent - 1] += number

for branch in branches:
    nodes[branch[1]] += nodes[branch[0]]

print(*nodes, sep=' ')

Submission status: Wrong Answer

Solution code:
N, Q = map(int, input().split())
edges = [input().split() for _ in range(N-1)]
operations = [input().split() for _ in range(Q)]

tree = {}
result = [0]*N
numbers = []

for o in operations:
    result[int(o[0])-1] += int(o[1])
print(result)

for e in edges:
    parent = int(e[0])
    sun = int(e[1])

    if sun in numbers:
        result[parent-1] += result[sun-1]
        numbers.append(parent)
    else:
        result[sun-1] += result[parent-1]
        numbers.append(sun)
    print(numbers)

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

Submission status: Wrong Answer

Solution code:
def main():
  n,q=map(int,input().split())
  a=[0]*n
  b=[0]*n
  c=[0 for i in range(n)]
  for i in range(n-1):
    a[i],b[i]=map(int,input().split())
  for i in range(q):
    x,y=map(int,input().split())
    c[x-1]+=y
  for i in range(n-1):
    c[b[i]-1]+=c[a[i]-1]
  print(*c)
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

C = {}
for i in range(N-1):
    a, b = map(int, input().split())
    if a > b:
        a, b = b, a
    if a not in C:
        C[a] = {'r': [b], 's': 0}
    else:
        C[a]['r'].append(b)

for i in range(Q):
    p, x = map(int, input().split())
    if p not in C:
        C[p] = {'r':[], 's': x}
    else:
        C[p]['s'] += x

# print(N, Q, C)

ans = []
for i in range(1, N):
    if i not in C:
        continue
    c = C[i]
    R = c['r']
    s = c['s']
    for r in R:
        if r not in C:
            C[r] = {'r': [], 's': s}
        else:
            C[r]['s'] += s
    ans.append(c['s'])

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict as dd
class Tree:
   def __init__(self, n):
        self.n = n
        self.tree = dd(list)
        self.value = dd(int)
    
   def addNode(self, u, v):
        self.tree[u].append(v)
    
   def update(self, u, n):
       self.value[u] += n
   
   def query(self,root):
       for node in self.tree[root]:
           self.value[node] += self.value[root]
           self.query(node)
   
   def ans(self):
       self.query(1)
       for i in xrange(1,self.n+1):
           print self.value[i],
       print ""

f = lambda : map(int, raw_input().split())

n, q = f()
tree = Tree(n)
for i in xrange(n - 1):
   tree.addNode(*f())
   
for i in xrange(q):
   tree.update(*f())
print ""
#tree.ans()

Submission status: Wrong Answer

Solution code:
import numpy as np
n, q =  list(map(int, input().split()))
x = [list(map(int, input().split())) for i in range(n-1)]
y = [list(map(int, input().split())) for i in range(q)]

res = np.zeros(n)
for i in range(q):
    res[y[i][0]-1] += y[i][1]
    for j in range(n-1):
        if x[j][0] >= y[i][0]:
            res[x[j][1]-1] += y[i][1]
for s in res:
  print(s, end =" ")

Submission status: Wrong Answer

Solution code:
N,Q = map(int,input().split())
ans = [0]*N
a = []
b = []
for i in range(1,N):
    ai,bi = map(int,input().split())
    a.append(ai)
    b.append(bi)
for j in range(Q):
    pj,xj = map(int,input().split())
    ans[pj-1] += xj
for i in range(N-1):
    ans[b[i]-1]+=ans[a[i]-1]
print(' '.join(map(str,ans)))

Submission status: Wrong Answer

Solution code:
n, q = map(int, input().split())
abab = [list(map(int, input().split())) for _ in range(n-1)]
pxpx = [list(map(int, input().split())) for _ in range(q)]

pxdict = {i:0 for i in range(1, 1+n)}
for p, x in pxpx :
    pxdict[p] += x
babadict = {b:a for a, b in abab}

ans = [pxdict[p] for p in range(1, 1+n)]
for a, b in abab :
    ans[b-1] += ans[a-1]
print(*ans)

Submission status: Wrong Answer

Solution code:
NQ = input().split(' ')
N = int(NQ[0])
Q = int(NQ[1])
candidate_list = []
tree_list = [[]] * N
#Make tree dict
for i in range(N-1):
    ab = input().split(' ')
    a = int(ab[0])
    b = int(ab[1])
    candidate_list.append((a,b))
candidate_list.reverse()
for candidate in candidate_list:
    a = candidate[0]
    b = candidate[1]
    tree_list[a-1] = tree_list[a-1] + tree_list[b-1]
    tree_list[a-1].append(b)
out_put_list = [0] * N
for _ in range(Q):
    px = input().split(' ')
    p = int(px[0])
    x = int(px[1])
    out_put_list[p-1] += x
    for idx in tree_list[p-1]:
        out_put_list[idx-1] += x
    
print(' '.join(map(str,out_put_list)))

Submission status: Wrong Answer

Solution code:
N, Q = map(int, input().split())
P = [0]*Q
X = [0]*Q

C = {}
for i in range(N-1):
    a, b = map(int, input().split())
    if a > b:
        a, b = b, a
    if a not in C:
        C[a] = {'r': [b], 's': 0}
    else:
        C[a]['r'].append(b)

for i in range(Q):
    p, x = map(int, input().split())
    if p not in C:
        C[p] = {'r':[], 's': x}
    else:
        C[p]['s'] += x

# print(N, Q, C)

ans = []
for i in range(1, N):
    if i not in C:
        continue
    c = C[i]
    R = c['r']
    s = c['s']
    for r in R:
        if r not in C:
            C[r] = {'r': [], 's': s}
        else:
            C[r]['s'] += s
    ans.append(c['s'])

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

Submission status: Wrong Answer

Solution code:
import collections

N, Q = [int(i) for i in input().split()]
edges = [[] for _ in range(N + 1)]
result = [0] * (N + 1)

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

for _ in range(Q):
    p, x = [int(i) for i in input().split()]

    q = collections.deque()
    q.append(p)

    while 0 < len(q):
        v = q.popleft()

        result[v] += x

        for u in edges[v]:
            q.append(u)

print(result[1:(N + 1)])

Submission status: Wrong Answer

Solution code:
N, Q = list(map(int, input().split()))
trees = {i: [] for i in range(1, N + 1)}
counter = {i: 0 for i in range(1, N + 1)}

for i in range(N-1):
    a, b = list(map(int, input().split()))
    trees[a].append(b)
    
for i in range(Q):
    p, x = list(map(int, input().split()))
    counter[p] += x
    for num in trees[p]:
        counter[num] += x
        for val in trees[num]:
            counter[val] += x

print(' '.join([str(i) for i in counter.values()]))

Submission status: Wrong Answer

Solution code:
N, Q = map(int, input().split())
P = [0]*Q
X = [0]*Q

C = {}
for i in range(N-1):
    a, b = map(int, input().split())
    if a > b:
        a, b = b, a
    if a not in C:
        C[a] = {'r': [b], 's': 0}
    else:
        C[a]['r'].append(b)

for i in range(Q):
    p, x = map(int, input().split())
    if p not in C:
        C[p] = {'r':[], 's': x}
    else:
        C[p]['s'] += x

print(N, Q, C)

ans = []
for i in range(1, N):
    if i not in C:
        continue
    c = C[i]
    R = c['r']
    s = c['s']
    for r in R:
        if r not in C:
            C[r] = {'r': [], 's': s}
        else:
            C[r]['s'] += s
    ans.append(c['s'])

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

Submission status: Wrong Answer

Solution code:
#import pysnooper
import os,re,sys,operator,math,heapq,string
from collections import Counter,deque
from operator import itemgetter
from itertools import accumulate,combinations,groupby
from sys import stdin,setrecursionlimit
from copy import deepcopy

setrecursionlimit(10**6)


n,q=map(int,stdin.readline().rstrip().split())
cnt=[0]*(n)
for i in range(n-1):
    a,b=map(int,stdin.readline().rstrip().split())

for i in range(q):
    p,x=map(int,stdin.readline().rstrip().split())
    cnt[p-1]+=x
for i in range(1,n):
    cnt[i]+=cnt[i-1]
print(*cnt)

Submission status: Wrong Answer

Solution code:
# Setup
import sys
import collections
sys.setrecursionlimit(4100000)

n,q = [int(i) for i in input().split()]
a = [[int(i) for i in input().split()] for _ in range(n-1)]
p = [[int(i) for i in input().split()] for _ in range(q)]

childs = collections.defaultdict(list)

for A,B in a:
    childs[A].append(B)

counter = collections.defaultdict(int)
affections = collections.defaultdict(list)

for A,B in p:
    counter[A] += B
    if affections.get(A):
        continue
    current = A
    aff = []
    tosee = [current]
    while len(tosee) != 0:
        temp = tosee.pop()
        aff.append(temp)
        for z in childs[temp]:
            if affections.get(z):
                aff += affections[z]
            else:
                tosee.append(z)
    affections[A] = aff
counts = collections.defaultdict(int)
for i in range(1,n+1):
    for z in affections[i]:
        counts[z] += counter[i]

ans = ""
for i in range(1,n+1):
    ans += str(counts[i]) + " "
print(ans,affections)

Submission status: Wrong Answer

Solution code:
n, q = map(int, input().split())
a = []
b = []
hens = []
for i in range (n-1):
  t_a, t_b = map(int, input().split())
  a.append(t_a-1)
  b.append(t_b-1)
  hens.append([t_a-1, t_b-1])
p = []
x = []
for i in range (q):
  t_p, t_x = map(int, input().split())
  p.append(t_p-1)
  x.append(t_x)
c = [0 for i in range(n)]
tree = [[None, [], False] for i in range(n)]
tree[0][2] = True

while(len(hens) >= 1):
  for hen in hens[:]:
    if tree[hen[0]][2] == True:
      tree[hen[0]][1].append(hen[1])
      tree[hen[1]][0] = hen[0]
      tree[hen[1]][2] = True
    elif tree[hen[1]][2] == True:
      tree[hen[1]][1].append(hen[0])
      tree[hen[0]][0] = hen[1]
      tree[hen[0]][2] = True
    hens.remove(hen)

def calc(p, x, ret):
  if len(tree[p][1]) == 0:
    ret[p] += x
  else:
    for child in tree[p][1]:
      ret = calc(child, x, ret)
    ret[p] += x
  return ret

ans = [0 for i in range(n)]
zr = [0 for i in range(n)]
for i in range(q):
  t_c = calc(p[i], x[i], zr)
  # ans = list(map(lambda x,y: x+y, ans, t_c))
  ans = [x+y for x,y in zip(ans, t_c)]
print(*ans)

Submission status: Wrong Answer

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

node_value = [0]*N

# ----------------------------------
table = [[]]*N
temp = []
for i in range(1,N+1):
    for j in range(N-1):
        if i == a[j]:
            temp.append(b[j])
    table[i-1] = temp
    temp = []
# ----------------------------------

def func(p, x):
    global table
    global node_value
    node_value[p-1] = node_value[p-1] + x

    leaflist =  table[p-1]
    if leaflist != []:
        for leaf in leaflist:
            func(leaf, x)

# ----------------------------------
# summation
for i in range(Q):
    func(p[i],x[i])
    
# ----------------------------------
    
for node in node_value:
  print(node, end=' ')

Submission status: Wrong Answer

Solution code:
NQ = input().split(' ')
N = int(NQ[0])
Q = int(NQ[1])
candidate_list = []
tree_dict = [[]] * N
#Make tree dict
for i in range(N-1):
    ab = input().split(' ')
    a = int(ab[0])
    b = int(ab[1])
    candidate_list.append((a,b))
candidate_list.reverse()
for candidate in candidate_list:
    a = candidate[0]
    b = candidate[1]
    tree_dict[a-1] += tree_dict[b-1] + [b-1]
        
out_put_list = [0] * N
for _ in range(Q):
    px = input().split(' ')
    p = int(px[0])
    x = int(px[1])
    out_put_list[p-1] += x
    for idx in tree_dict[p-1]:
        out_put_list[idx-1] += x
    
print(' '.join(map(str,out_put_list)))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict as dd
class Tree:
   def __init__(self, n):
        self.n = n
        self.tree = dd(list)
        self.value = dd(int)
    
   def addNode(self, u, v):
        self.tree[u].append(v)
    
   def update(self, u, n):
       self.value[u] += n
   
   def query(self,root):
       for node in self.tree[root]:
           self.value[node] += self.value[root]
           self.query(node)
   
   def ans(self):
       self.query(1)
       for i in xrange(1,self.n+1):
           print self.value[i],
       print ""

f = lambda : map(int, raw_input().split())
try:
  n, q = f()
  tree = Tree(n)
  for i in xrange(n - 1):
    tree.addNode(*f())

  for i in xrange(q):
     tree.update(*f())
  tree.ans()
except:
    print ""

Submission status: Wrong Answer

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

tree = [[i] for i in range(N+1)]
tree_parent = [0] * (N+1)
points = [0] * N

for i in range(1, N):
  a, b = map(int, input().split())
  tree[a].append(b)
  tree_parent[b] = a
  if tree_parent[a] != 0:
	  tree[tree_parent[a]].append(b)
    
for i in range(Q):
  p, x = map(int, input().split())
  for node in set(tree[p]):
    points[node-1] += x

print(*points)
"""    
for point in points:
  print(point, end=" ")
"""

Submission status: Wrong Answer

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

ans = [0]*N  
L = []
L2 = [[0] for _ in range(N)]

for i in range(N-1):
  route = []
  if b[i] not in a:
    route.append(b[i])
    var = a[i]
    while True:
      if var in b:
        route.append(var)
        var = a[b.index(var)]
      else:
        route.append(int(1))
        break
  if len(route) > 0:
    L.append(route)
  
for i in range(len(L)):
  for j in range(len(L[i])):
    while(j >= 1):
      L2[L[i][j]].append(L[i][j-1])
      j -= 1
print(L2)
      
for i in range(Q):
  if p[i] in a:
    var = 0
  else:
    ans[i] += x[i]


print(*ans)

Submission status: Wrong Answer

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


tree={}
result={}

temp=[]
#print(n-1)
for _ in range(n-1):
  temp.append(list(map(int,input().split())))

temp=temp[::-1]
#print(temp)
  
for a,b in temp:
  if a in tree:
    tree[a].append(b)
  else:
    tree[a]=[b]
  if b in tree:
    for k in tree[b]:
      tree[a].append(k)
  else:
    tree[b]=[]
 # print(a,b,tree)


  
for _ in range(q):
  no,value=map(int,input().split())
  if no in result:
    result[no]+=value
  else:
    result[no]=value

  for j in tree[no]:
    if j in result:
      result[j]+=value
    else:
      result[j]=value
    
  
print(*result.values())

Submission status: Wrong Answer

Solution code:
import logging

logging.basicConfig(level=logging.INFO, format="%(message)s")
#logging.disable(logging.CRITICAL)



def main():
    N, Q = map(int, input().split())
    a_b = sorted([list(map(int, input().split())) for _ in range(N - 1)])
    p_x = sorted([list(map(int, input().split())) for _ in range(Q)])
    score = [0 for _ in range(N)]

    for task in p_x:
        score[task[0] - 1] = task[1]

    
    for leef in a_b:
        score[leef[1] - 1] += score[leef[0] - 1]   

        
    answer = ""
    for i in score:
        answer += str(i)
        answer += " "

    print(answer)
    
    
if __name__ == "__main__":
    main()