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:
n, q =  map(int, raw_input().split())
graph = dict()
operation = [0 for i in range(q)]
for i in range(n-1):
    a, b = map(int, raw_input().split())
    if a in graph.keys():
        graph[a].add(b)
    else:
        graph[a] = set([b])
    if b in graph.keys():
        graph[b].add(a)
    else:
        graph[b] = set([a])

for i in range(q):
    operation[i] = [int(j) for j in raw_input().split()]

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

def dfs(graphx, vertex, check, value):
    check[vertex-1] = True
    values[vertex-1] += value
    for v in graph[vertex]:
        if check[v - 1] == True:
            continue
        dfs(graphx, v, check, value)


for i in range(q):
    check_list = [False for j in range(n)]
    ver = operation[i][0]
    for v in graph[ver]:
        if v < ver:
            check_list[v-1] = True
    print(operation[i])
    dfs(graph, operation[i][0], check_list, operation[i][1])

mapped_values = map(str, values)

result = ""
for i in range(n):
    result += mapped_values[i]
    if i < n - 1:
        result += " "

print(result)

Submission status: Wrong Answer

Solution code:


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

a = [0] * (N - 1)
b = [0] * (N - 1)

p = [0] * Q
x = [0] * Q

point = [0] * N

def kasan(n, y):
    z = 0
    for i in range(Q):
        
        if p[i] == n:
            z += x[i]
    for i in range(N - 1):
        if a[i] == n:
            kasan(b[i],y + z)
    
    point[n - 1] += y + z

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

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

kasan(1,0)

print(point)

Submission status: Wrong Answer

Solution code:
N, Q = (int(i) for i in input().split())
a_b = [[int(i) for i in input().split()] for i in range(N - 1)]
p_x = [[int(i) for i in input().split()] for i in range(Q)]

child = {}
parent = {}
node_list = set()
for ab in a_b:
    parent[ab[1]] = ab[0]
    child[ab[0]] = child.get(ab[0], [])
    child[ab[0]].append(ab[1])
    node_list.add(ab[0])
    node_list.add(ab[1])

for k, v in child.items():
    if k != 1:
        child[parent[k]] += v

print("test")

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n,q=map(int,input().split())
a=[[0,0] for _ in range(n-1)]
for i in range(n-1):
    a[i][0],a[i][1]=map(int,input().split())
p=[[0,0] for _ in range(q)]
for k in range(q):
    p[k][0],p[k][1]=map(int,input().split())
p.sort()
t=[[i] for i in range(1,n+1)]
ans=[0 for _ in range(n)]
for i in range(q):
    ans[p[i][0]-1]+=p[i][1]
for i in range(n-1):
    ans[a[i][1]-1]+=ans[a[i][0]-1]   
print(' '.join(map(str,ans)))

Submission status: Wrong Answer

Solution code:
N, Q = map(int,input().split())
l = [list(map(int,input().split())) for _ in range(N-1)]
m = [list(map(int,input().split())) for _ in range(Q)]
ll = [0]*N
bb = [[i] for i in range(1,N+1)]
for i in l:
    bb[i[0]-1].append(i[1])
for i in m:
    ll[i[0]-1] += int(i[1])
ans = [0]*N
# print("bb=",bb)
# print("ll=",ll)
for i in range(N):
    for k in bb[i]:
        if k == i+1:
            ans[i] += ll[i]
        else:
            ll[k-1] += ll[i]

Submission status: Wrong Answer

Solution code:
from collections import deque
n, q = map(int, input().split())
connect = [[] for _ in range(n)]
count = [0] * n
for i in range(n-1):
    a, b = map(int, input().split())
    connect[a-1].append(b-1)
print('connect{}'.format(connect))

operate = []
for _ in range(q):
    operate.append(tuple(map(int, input().split())))
print('operate{}'.format(operate))

for p, x in operate:
    que = deque([])
    que.append(p-1)
    print('que{}'.format(que))

    while que:
        t = que.popleft()
        count[t] += x
        sakis = connect[t]
        for saki in sakis:
            que.append(saki)
    
for c in count:
    print(c, end = ' ')
    print('\n')

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
N, Q = map(int, input().split())

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

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

children = defaultdict(set)
for i in range(1,N+1):
    children[i].add(i)
    d = deque(connection[i])
    checked = set(connection[i])
    while len(d) > 0:
        x = d.popleft()
        children[i].add(x)
        d += connection[x]

ans = []
for i in range(1, N+1):
    cnt = 0
    for v in children[i]:
        cnt += operations[v]
        print(cnt)
    ans.append(str(cnt))
print(' '.join(ans))

Submission status: Wrong Answer

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

# make tree dictionary
dic = {}
for i in range(1, N):
    a, b = map(int, input().split())
    if a in dic.keys():
        dic[a].append(b)
    else:
        dic[a] = [b]

# make result list
result = [0] * N

# calc result
for k in range (1, Q + 1):
    top, x = map(int, input().split())
    result[top-1] += x
    p1 = [top]
    while p1[0] in dic.keys(): #when top is in dic
        for p2 in dic[p1[0]]:
            result[p2-1] += x
            p1.append(p2)
        del p1[0]

print (result)

Submission status: Wrong Answer

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

N, Q = map(int, input().split())
a = []
p = []
x = [0]*(N)
A = [0]*(N)

for i in range(N-1):
    t=input().split()
    if t[0]>t[1]:
        swap = t[1]
        t[1] = t[0]
        t[0] =swap
    a.append((int(t[0]),int(t[1])))
for i in range(Q):
    t=input().split()
    p.append((int(t[0]),int(t[1])))

a =sorted(a, key=lambda x: x[0])
p =sorted(p, key=lambda x: x[0])

#print(a)
for i in range(Q):
    x[p[i][0]-1] += p[i][1]
for i in range(N):
    A[i] = x[i]
for i in range(N-1):
    La = a[i][0]-1
    Lb = a[i][1]-1

    A[Lb] = A[La]+x[Lb]

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

Submission status: Wrong Answer

Solution code:
from sys import setrecursionlimit, stdin

setrecursionlimit(100000)


class Node:
    def __init__(self, num):
        self.num = num
        self.children = []
        self.value = 0

    def append(self, child):
        self.children.append(child)

    def add_value(self, value):
        self.value += value


def spam(nodes, dic1, dic2, flags, num):
    index = num - 1
    flags[index] = True
    node = nodes[index]
    nums = dic1.get(num, []) + dic2.get(num, [])
    nums = [x for x in nums if not flags[x - 1]]
    for n in nums:
        node.append(nodes[n - 1])
        spam(nodes, dic1, dic2, flags, n)


def ham(nodes, num, value):
    index = num - 1
    node = nodes[index]
    node.add_value(value)
    for n in node.children:
        ham(nodes, n.num, value)


def main():
    N, Q = [int(x) for x in stdin.readline().rstrip().split()]
    ab = [[int(x) for x in stdin.readline().rstrip().split()] for _ in range(N - 1)]
    px = [[int(x) for x in stdin.readline().rstrip().split()] for _ in range(Q)]
    dic1 = {}
    dic2 = {}
    flags = [False for _ in range(N)]
    for a, b in ab:
        if a in dic1:
            dic1[a].append(b)
        else:
            dic1[a] = [b]
        if b in dic2:
            dic2[b].append(a)
        else:
            dic2[b] = [a]
    nodes = [Node(i + 1) for i in range(N)]
    spam(nodes, dic1, dic2, flags, 1)
    # for p, x in px:
    #     ham(nodes, p, x)
    for n in nodes:
        print(n.value, end=' ')
    print('')


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n, q =  map(int, raw_input().split())
graph = dict()
operation = [0 for i in range(q)]
for i in range(n-1):
    a, b = map(int, raw_input().split())
    if a in graph.keys():
        graph[a].add(b)
    else:
        graph[a] = set([b])
    if b in graph.keys():
        graph[b].add(a)
    else:
        graph[b] = set([a])

for i in range(q):
    operation[i] = [int(j) for j in raw_input().split()]

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

def dfs(graphx, vertex, check, value):
    check[vertex-1] = True
    values[vertex-1] += value
    for v in graph[vertex]:
        if check[v - 1] == True:
            continue
        dfs(graphx, v, check, value)


for i in range(q):
    check_list = [False for j in range(n)]
    ver = operation[i][0]
    for v in graph[ver]:
        if v < ver:
            check_list[v-1] = True
    print(operation[i])
    dfs(graph, operation[i][0], check_list, operation[i][1])

mapped_values = map(str, values)
result = " ".join(mapped_values)
print(result)

Submission status: Wrong Answer

Solution code:
N, Q = map(int, input().split())
tree_data = [tuple(map(int, input().split())) for i in range(N - 1)]
operation = [tuple(map(int, input().split())) for i in range(Q)]

node = dict(zip(range(1, N + 1), [0] * N))
for o in operation:
    node[o[0]] += o[1]

for n in tree_data:
    node[n[1]] += node[n[0]]

print(' '.join(map(str, node.values())))

Submission status: Wrong Answer

Solution code:
from collections import deque
n, q = map(int, input().split())
connect = [[] for _ in range(n)]
count = [0] * n
for i in range(n-1):
    a, b = map(int, input().split())
    connect[a-1].append(b-1)
print('connect{}'.format(connect))

operate = []
for _ in range(q):
    operate.append(tuple(map(int, input().split())))
print('operate{}'.format(operate))

for p, x in operate:
    que = deque([])
    que.append(p-1)
    print('que{}'.format(que))

    while que:
        t = que.popleft()
        count[t] += x
        sakis = connect[t]
        for saki in sakis:
            que.append(saki)
    
for c in count:
    print(c, end = ' ')

Submission status: Wrong Answer

Solution code:

def main():
    
    
    in1 = [int(e) for e in input().split()]
    n = in1[0]
    q = in1[1]

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

    p = []
    x = []
    for i in range(q):
        in1 = [int(e) for e in input().split()]
        p.append(in1[0])
        x.append(in1[1])

    l = [0] * n

    def addval(p,x):
        l[p-1] += x

        for j in range(p,n-1):
            #print('j',j)
            if(a[j] == p):
                addval(b[j],x)

    for i in range(q):
        addval(p[i],x[i])

    
    for i in range(n):
        print(l[i], end="")
        print(" ", end="")
        




if __name__ == "__main__":
    main()

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):
    p[i], x[i] = list(map(int, input().split()))
    
trees = {}
counter = {i: 0 for i in range(1, N + 1)}

for i in range(N-1):
    if a[i] in trees.keys():
        trees[a[i]].append(b[i])
    else:
        trees[a[i]] = [b[i]]
        
for i in range(Q):
    if p[i] not in trees.keys():
        print(p[i])
        counter[p[i]] += x[i]
    else:
        counter[p[i]] += x[i]
        for num in trees[p[i]]:
            counter[num] += x[i]
            if num in trees.keys():
                for val in trees[num]:
                    counter[val] += x[i]

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

Submission status: Wrong Answer

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

b = []
for j in range(q):
    b.append((input()))
    
aws = []
for k in range(n):
    aws.append(0)
    
def tree(t_num,point):
    aws[t_num - 1] +=  point
    for an in a:
        if t_num == int(an.split()[0]):
            tree(int(an.split()[1]),point)
for bn in b:
    t_num = int(bn.split()[0])
    point = int(bn.split()[1])
    tree(t_num,point)
    
print(aws)

Submission status: Wrong Answer

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

dic = defaultdict(list)
n, q = map(int, input().split())

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

tree = [0]*(n+1)

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

todo = deque([1])
while todo:
    root = todo.popleft()
    count = tree[root]
    children = dic[root]
    for to in children:
        tree[to] += count
        todo.append(to)

print(' '.join(map(str, tree)).lstrip(' 0 '))

Submission status: Wrong Answer

Solution code:
n, q = list(map(int, input().split()))
ab = [input() for i in range(n-1)]
ans = [0] * n
p = [list(map(int, input().split())) for i in range(q)]
for i, j in p:
  if i > n-2:
    ans[i-1] += j
  else:
    ans = ans[:i-1] + [k + j for k in ans[i-1:]]
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 18 21:19:43 2019
ABC138D
@author: maezawa
"""

n, q = list(map(int, input().split()))
graph = [[] for _ in range(n+1)]
for _ in range(n-1):
    ai, bi = list(map(int, input().split()))
    graph[ai].append(bi)
    graph[bi].append(ai)
    
parent = [[] for _ in range(n+1)]
child = [[] for _ in range(n+1)]
current = 1
while current <= n:
    for j in graph[current]:
        if current in child[j]:
            continue
        child[current].append(j)
    current += 1
#print(child)
parray = [-1]*(n+1)
parray[1] = 0
for i in range(1,n+1):
    for j in child[i]:
        parray[j] = i
#print(parray)
tpoint = [0]*(n+1)
for i in range(q):
    pi, xi = list(map(int, input().split()))
    tpoint[pi] += xi
tpmem = [-1]*(n+1)
tpmem[1] = tpoint[i]
for i in range(1, n+1):
    pi = 0
    j = i
    while True:
        if tpmem[j] != -1:
            pi += tpmem[j]
            break
        pi += tpoint[j]
        if parray[j] == -1:
            break
        j = parray[j]
    print(pi)
    tpmem[i] = pi

Submission status: Wrong Answer

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

N, Q = map(int, input().split())
a = []
p = []
x = [0]*(N)
A = [0]*(N)

for i in range(N-1):
    t=input().split()
    if t[0]>t[1]:
        swap = t[1]
        t[1] = t[0]
        t[0] =swap
    a.append((int(t[0]),int(t[1])))
for i in range(Q):
    t=input().split()
    p.append((int(t[0]),int(t[1])))

a.sort()
p.sort()

#print(a)
for i in range(Q):
    x[p[i][0]-1] += p[i][1]
for i in range(N):
    A[i] = x[i]
for i in range(N-1):
    La = a[i][0]-1
    Lb = a[i][1]-1

    A[Lb] = A[La]+x[Lb]

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

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

temp=[[i+1] for i in range(n)]
for i in range(n-2,-1,-1):
    if len(temp[ab[i][1]-1]) >= 2:
        temp[ab[i][0]-1].extend(temp[ab[i][1]-1])
    else:
        temp[ab[i][0]-1].append(ab[i][1]) 


ans=[0 for i in range(n)]
for j in range(q):
    for _ in temp[px[j][0]-1]:
        ans[_-1]+=px[j][1]

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

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

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

score = defaultdict(int)
for i in range(q):
    p, x = list(map(int,input().split()))
    score[p] += x
    target = data[p]
    pos = 0
    while pos < len(target):
        target += data[target[pos]]
        pos += 1
    for t in target:
        score[t] += x

scorelist = []
for i in range(n):
    s = str(score[i+1])
    scorelist.append(s)
print(' '.join(scorelist))

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)]
ans = [0]*n
parent=[1]
while ab!=[]:
  for i in parent:
    l=[j[1] for j in px if j[0]==i]
    ans[i-1]+=sum(l)
    parent=[sum(k)-i for k in ab if k[0]==i or k[1]==i]
    ab=[k for k in ab if k[0]!=i and k[1]!=i]
    for m in parent:
      ans[m-1]+=ans[i-1]
for i in parent:
  l=[j[1] for j in px if j[0]==i]
  ans[i-1]+=sum(l)
print(ans)

Submission status: Wrong Answer

Solution code:
n,q=map(int,input().split())
a=[]
b=[]
s=[0]


for i in range(0,n-1):
    A,B=map(int,input().split())
    a.append(A)
    b.append(B)
    s.append(0)
for i in range(0,q):
    P,X=map(int,input().split())
    s[P-1]=s[P-1]+X


for j in range(0,n-1):
    s[b[j]-1]=s[b[j]-1]+s[a[j]-1]

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

Submission status: Wrong Answer

Solution code:
n, q = map(int, input().split())
a_b = [[] for i in range(n-1)]
for i in range(n-1):
    a_b[i] = list(map(int, input().split()))
a_b_lst = [[] for i in range(n)]
for i in range(n-1):
    a_b_lst[a_b[i][0]-1].append(a_b[i][1])
o_g_dict = dict(zip([i+1 for i in range(n)], [0]*n))
for i in range(q):
    p_x = list(map(int, input().split()))
    o_g_dict[p_x[0]] += p_x[1]
    for j in a_b_lst[p_x[0]-1]:
        o_g_dict[j] += p_x[1]
        for k in a_b_lst[j-1]:
            o_g_dict[k] += p_x[1]
print(' '.join(list(map(str, o_g_dict.values()))))

Submission status: Wrong Answer

Solution code:
import numpy as np
def listAppend(list, edgeList, searchNumber):
    for e in edgeList:
        if e[0] == searchNumber:
            if not(e[1] in list):
                list.append(e[1])
                list = listAppend(list, edgeList, e[1])
    return list

N, Q = list(map(int, input().split())) # 整数
d = []
for i in range(N+Q-1):
    d.append(list(map(int, input().split())))
A = d[0:N-1]
P = d[N-1:N-1+Q]

sumList = np.repeat(0, N)

for p in P:
    tempList = listAppend(list(), A, p[0])
    tempList.append(p[0])
    print(tempList)

    for i in tempList:
        sumList[i-1] += p[1]
print(' '.join(map(str, sumList)))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[3]:


from sys import stdin
input = stdin.readline

N, Q = map(int, input().split())
abs_ = [list(map(int, input().split())) for _ in range(N-1)]
pxs_ = [list(map(int, input().split())) for _ in range(Q)]


# In[4]:


class Node:
    def __init__(self, nb, data): #コンストラクタ
        self.nb = nb
        self.data = data #ノードがもつ数値
        self.parent = -1 # nodeがrootのとき-1、それ以外番号
        self.childs = [] # childになるnode classが入る
        
    def connect_childs(self, child_class_):
        self.childs.append(child_class_)


# In[11]:


nodes = [Node(_+1, 0) for _ in range(N)]


# In[12]:


for i in range(N-1):
    a, b = abs_[i]
    nodes[a-1].connect_childs(nodes[b-1])
    nodes[b-1].parent = a-1


# In[13]:


for i in range(Q):
    p, x = pxs_[i]
    nodes[p-1].data += x


# In[14]:


def sum_data_to_childs(nodes):
    datas = [0]*N
    
    datas[0] = nodes[0].data
    
    for i in range(1, N):
        nodes[i].data += nodes[nodes[i].parent].data
        print(nodes[i].data)
        datas[i] = nodes[i].data
        
    return datas


# In[15]:


datas = sum_data_to_childs(nodes)


# In[16]:


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


# In[ ]:

Submission status: Wrong Answer

Solution code:
line = input().split()
N = int(line[0])
Q = int(line[1])
g = {}
g2 = {}
for i in range(N-1):
    r = input().split()
    a = int(r[0])
    b = int(r[1])
    if not a in g:
        g[a] = [b]
    else:
        g[a].append(b)
    g[b] = []
    g2[b] = a

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

for i in range(Q):
    row = input().split()
    p = int(row[0])
    x = int(row[1])
    suma[p-1] += x

idx = 0
def add(parent):
    chi = g[parent]
    for c in chi:
        suma[c-1] += suma[parent-1] 
        add(c)
add(1)
for i in range(0,N-1):
    print(suma[i], end=' ')
print(suma[N-1])

Submission status: Wrong Answer

Solution code:
N, Q = map(int, input().split())
a = []
b = []
for _ in range(N-1):
    s,t  = map(int,input().split())
    a.append(s)
    b.append(t)
p = {}
for _ in range(Q):
    s,t  = map(int,input().split())
    if s in p.keys():
        p[s] = p[s] + t
    else:
        p[s] = t

for i in range(N-1):
    s = a[i]
    t = b[i]
    if t in p.keys() and s in p.keys():
      p[t] += p[s]
    elif t in p.keys():
      p[s] = 0
      continue
    elif s in p.keys():
      p[t] = p[s]
    else:
      p[s] = 0
      p[t] = 0

for v in p.values():
  print(str(v)+" ",end="")

Submission status: Wrong Answer

Solution code:
def main():
    n, q = map(int, input().split())
    C = [list(map(int, input().split())) for i in range(n-1)]
    D = [list(map(int, input().split())) for i in range(q)]
    J, K, L = {}, {}, {}

    for c in C:
        if c[0] not in J:
            J[c[0]] = [c[1]]
        else:
            J[c[0]].append(c[1])

    for k, v in J.items():
        L[k] = [i for i in v]
        for i in L[k]:
            if i in list(J.keys()):
                L[k] += J[i]

    for d in D:
        if d[0] not in K:
            K[d[0]] = d[1]
        else:
            K[d[0]] += d[1]

    ans = [0 for i in range(n)]
    for k, v in K.items():
        ans[k-1] += v
        if k in L:
            for i in L[k]:
                ans[i-1] += v

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10000000)

class tree:
    def __init__(self):
        self.baby_list=[]
        self.counter=0
    
    def add_value(self):
        for i in self.baby_list:
            hoge[i].counter += self.counter
            hoge[i].add_value()

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


hoge={}

for i in range(1,N+1):
    hoge[str(i)] = tree()
    
for i in range(N-1):
    a,b=input().split()
    hoge[a].baby_list.append(b)

for i in range(Q):
    root, value = input().split()
    hoge[root].counter+=int(value)

hoge["1"].add_value()
output = ""
for t in hoge:
    output+=str(hoge[t].counter)+" "

print(output[:-1])

Submission status: Wrong Answer

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


def flatten(data):
    return [element
            for item in data
            for element in (flatten(item) if hasattr(item, '__iter__') else [item])]

def search_append(tree,an,bn):
    if an in tree:
        tree.append([bn])
    else:
        for j in tree:
            if isinstance(j,list):
                search_append(j,an,bn)

def search_count(tree,counter,pn,xn):
    if pn in tree:
        for i in flatten(tree):
            counter[i-1]+=xn

    else:
        for j in tree:
            if isinstance(j,list):
                search_count(j,counter,pn,xn)


t=[1]

for i in range(n-1):
    a,b=input().split()
    a,b=int(a),int(b)
    search_append(t,a,b)

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

for i in range(q):
    p,x=input().split()
    p,x=int(p),int(x)
    search_count(t,c,p,x)

for i in range(n):
    print(c[i],end=" ")

print("")

Submission status: Wrong Answer

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

N, Q = map(int, input().split())
a = []
p = []
x = [0]*(N)
A = [0]*(N)

for i in range(N-1):
    t=input().split()
    if t[0]>t[1]:
        swap = t[1]
        t[1] = t[0]
        t[0] =swap
    a.append((int(t[0]),int(t[1])))
for i in range(Q):
    t=input().split()
    p.append((int(t[0]),int(t[1])))

a.sort()
p.sort()

#print(a)
for i in range(Q):
    x[p[i][0]-1] += p[i][1]
A[0] = x[0]
for i in range(N-1):
    La = a[i][0]-1
    Lb = a[i][1]-1

    A[Lb] = A[La]+x[Lb]

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

Submission status: Wrong Answer

Solution code:
import sys

input = sys.stdin.readline

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

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

manips = {}
for i in range(Q):
    p, x = map(int, input().strip().split(' '))
    manips.setdefault(p, [])
    manips[p].append(x)

mat = [0] * (N + 1)
for i in range(N):
    if i in manips.keys():
        for x in manips[i]:
            mat[i] += x

    if i in tree.keys():
        for node in tree[i]:
            mat[node] += mat[i]

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

Submission status: Wrong Answer

Solution code:
from collections import deque
n, q = map(int, input().split())
connect = [[] for _ in range(n)]
count = [0] * n
for i in range(n-1):
    a, b = map(int, input().split())
    connect[a-1].append(b-1)

operate = []
for _ in range(q):
    operate.append(tuple(map(int, input().split())))

for p, x in operate:
    que = deque([])
    que.append(p-1)

    while que:
        t = que.popleft()
        count[t-1] += x
        sakis = connect[t]
        for saki in sakis:
            que.append(saki)
    
for c in count:
    print(c, end = ' ')

Submission status: Wrong Answer

Solution code:
n, q = list(map(int, input().split()))
ab = [list(map(int, input().split())) for i in range(n-1)]
ans = [0] * n
p = [list(map(int, input().split())) for i in range(q)]
for i, j in p:
  if i > n-2:
    ans[i-1] += j
  else:
    ans = ans[:i-1] + [k + j for k in ans[i-1:]]
print(ans)

Submission status: Wrong Answer

Solution code:
n, q =  map(int, raw_input().split())
graph = dict()
operation = [0 for i in range(q)]
for i in range(n-1):
    a, b = map(int, raw_input().split())
    if a in graph.keys():
        graph[a].add(b)
    else:
        graph[a] = set([b])
    if b in graph.keys():
        graph[b].add(a)
    else:
        graph[b] = set([a])

for i in range(q):
    operation[i] = [int(j) for j in raw_input().split()]

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

def dfs(graphx, vertex, check, value):
    check[vertex-1] = True
    values[vertex-1] += value
    for v in graph[vertex]:
        if v < vertex or check[v - 1] == True:
            continue
        dfs(graphx, v, check, value)


for i in range(q):
    check_list = [False for j in range(n)]
    print(operation[i])
    dfs(graph, operation[i][0], check_list, operation[i][1])

mapped_values = map(str, values)
result = " ".join(mapped_values)
print(result)

Submission status: Wrong Answer

Solution code:
N,Q = [int(s) for s in input().split(" ")]

def linkedSum(inList, x):
    if 0 < len(inList):
        for i,node in enumerate(inList):
            #print(i,p,x)
            sumList[node] += x
            if i != 0:
                linkedSum(treeList[node][1:], x)
    
treeList = [[i] for i in range(N)]
sumList = [0 for i in range(N)]

for i in range(N-1):
    a, b = [int(s) for s in input().split(" ")]
    treeList[a-1].append(b-1)
#print(treeList)    
for i in range(Q):
    p,x = [int(s) for s in input().split(" ")]
    edges = treeList[p-1]
    linkedSum(edges, x)
    
sumStrList = map(str, sumList)
print(" ".join(sumStrList))

Submission status: Wrong Answer

Solution code:
N,Q =map(int,input().split())
A = sorted([list(map(int,input().split())) for i in range(N-1)])
C = sorted([list(map(int,input().split())) for i in range(Q)])
for j in range(Q-1):
    if C[j][0] == C[j+1][0]:
        C[j][1] += C[j+1][1]
        C.pop(j+1)
lists = [0 for _ in range(N)]
try:
    for k in range(N):
        lists[k] = C[k][1]
except:
    pass
try:
    for k in range(N):
        lists[A[k][1]-1] +=lists[A[k][0]-1]
except:
    pass
print(' '.join(map(str,lists)))

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10 ** 9)

N, Q = map(int, input().split())
repn = [[] for i in range(N)]

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

count = [0] * N

## analysis of tree structure
parent = [-1] + ['nul'] * (N - 1)
child = [[] for i in range(N)]
child[0] = repn[0]

for v in child[0]:
    parent[v] = 0

deq = deque(repn[0])

while deq:
    v = deq.popleft()
    for w in repn[v]:
        if parent[v] == w:
            pass
        else:
            parent[w] = v
            child[v].append(w)
            deq.append(w)

multi_child = [[] for i in range(N)]
for i in range(N):
    multi_child[i].append(i)
    v = parent[i]
    while v != -1:
        multi_child[v].append(i)
        v = parent[v]

print(multi_child)

# make a function
def add(lst, p, x):
    if child[p] == []:
        lst[p] += x
    else:
        lst[p] += x
        for v in child[p]:
            add(lst, v, x)

## soltion
for i in range(Q):
    p, x = map(int, input().split())
    p -= 1
    for v in multi_child[p]:
        count[v] += x
    
print(' '.join(map(str, count)))

Submission status: Wrong Answer

Solution code:
N,Q=map(int,input().split())
l=[[] for i in range(N)]
ans=[0 for i in range(N)]
for i in range(N-1):
  a,b=map(int,input().split())
  l[a-1].append(b-1)
  l[b-1].append(a-1)
#print(l)

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

for i in range(Q):
  a,b=map(int,input().split())
  dic[a-1]+=b
#print(dic)

nex=[0]
no=[0]
an=0

while an<N-1:
  no=nex
  nex=[]
  #print("no",no,"ans",ans)
  for j in no:
    ans[j]+=dic[j]
    an+=1
    for i in l[j]:
      l[i].remove(j)
      ans[i]=ans[j]
      #ans[j]=str(ans[j])
      
      nex.append(i)
      #print(j,"i",i,"l[i]",l[i],ans,nex)
      

for i in range(N):
  ans[i]=str(ans[i])
  
print(" ".join(ans))