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
sys.setrecursionlimit(1000000)
N,Q = list(map(int,input().split()))
to = [[] for _ in range(N+1)]
ans = [0 for _ in range(N+1)]

for _ in range(N-1):
    ab=list(map(int,input().split()))
    print(ab[0], ab[1])
    to[ab[0]].append(ab[1])
    to[ab[1]].append(ab[0])
for _ in range(Q):
    px = list(map(int,input().split()))
    ans[px[0]] += px[1]

def dfs(v, p):
    for u in to[v]:
        if u == p:
            continue
        ans[u] += ans[v]
        dfs(u, v)
dfs(1, -1)
print(*ans[1:])

Submission status: Wrong Answer

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

def main():
  N,Q = map(int,input().split())
  trees = [[] for _ in range(N+1)]
  values = [0 for _ in range(N+1)]

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

  for _ in range(Q):
    node_num,value = map(int,input().split())
    values[node_num] += value

  # def recursive_func(i,parent):
  #   for child in trees[i]:
  #     if child == parent:
  #       continue
  #     values[child] += values[i]
  #     recursive_func(child,i)

  def recursive_func(parent):
    for child in trees[parent]:
      values[child] += values[parent]
      recursive_func(child)

  recursive_func(1)
  print(*values[1:])

main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(1000000)


def main():
  N,Q = map(int,input().split())
  trees = [[] for _ in range(N+1)]
  values = [0 for _ in range(N+1)]
  
  for _ in range(N-1):
    parent,child = map(int,input().split())
    trees[parent].append(child)
  
  for _ in range(Q):
    node_num,value = map(int,input().split())
    values[node_num] += value
  
  def recursive_func(parent):
    for child in trees[parent]:
      values[child] += values[parent]
      recursive_func(child)
  
  recursive_func(1)
  print(*values[1:])


if __name__ == "__main__":
  main()

Submission status: Wrong Answer

Solution code:
#abc138d

n,q=map(int,raw_input().split())
ab=[]
for i in xrange(n-1):
 a,b=map(int,raw_input().split())
 ab.append([a,b])
px=[]
for i in xrange(q):
 p,x=map(int,raw_input().split())
 px.append([p,x])
num=[0]*n
for p,x in px:
 num[p-1]+=x
ab.sort()
for a,b in ab:
 num[b-1]+=num[a-1]
for i in xrange(n):
 print num[i],
print

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
n, q = map(int, input().split())

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

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

def dfs(i):
    for j in trees[i]:
        values[j] += values[i]
        dfs(j)

dfs(0)
print(*values)

Submission status: Wrong Answer

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


N,Q=map(int,input().split())
EDGE=[list(map(int,input().split())) for i in range(N-1)]
PLUS=[list(map(int,input().split())) for i in range(Q)]

SCORE=[0]*(N+1)
for p,x in PLUS:
    SCORE[p]+=x

ELIST=[[] for i in range(N+1)]

for x,y in EDGE:
    ELIST[x].append(y)
    ELIST[y].append(x)
#print(ELIST)

from collections import deque
Q=deque([1])

USED=[0]*(N+1)
USED[1]=1
#USED = [0, 1, 0, 0, 0] Ex1
#SCORE = [0, 100, 10, 1, 0] Ex1
#ELIST = [[], [2], [1, 3, 4], [2], [2]] Ex1

while Q:
    x=Q.pop()
    print(x)

    for to in ELIST[x]:
        if USED[to]==0:
            USED[to]=1
            SCORE[to]+=SCORE[x]
            Q.append(to)

print(*SCORE[1:])

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(1000000)

class Node(object):
  def __init__(self,name):
    self.name = name
    self.value = 0

def main():
  N,Q = map(int,input().split())
  nodes = {}
  combs = []
  tasks = []

  for _ in range(N-1):
    parent,child = map(int,input().split())
    nodes.update({parent:Node(parent)})
    nodes.update({child:Node(child)})
    combs.append((parent,child))
  
  for _ in range(Q):
    node_name,value = map(int,input().split())
    tasks.append((node_name,value))
  
  for node_name,value in tasks:
    node = nodes[node_name]
    node.value += value

  for parent,child in sorted(combs,key=lambda x:x[0]):
    nodes[child].value += nodes[parent].value
  
  lst = sorted(nodes.values(),key=lambda x:x.name)
  print(" ".join([str(node.value) for node in lst]))



if __name__ == "__main__":
  main()

Submission status: Wrong Answer

Solution code:

class Node(object):
  def __init__(self,name):
    self.name = name
    self.value = 0

def main():
  N,Q = map(int,input().split())
  nodes = {}
  combs = []
  tasks = []

  for _ in range(N-1):
    parent,child = map(int,input().split())
    nodes.update({parent:Node(parent)})
    nodes.update({child:Node(child)})
    combs.append((parent,child))
  
  for _ in range(Q):
    node_name,value = map(int,input().split())
    tasks.append((node_name,value))
  
  for node_name,value in tasks:
    node = nodes[node_name]
    node.value += value

  for parent,child in sorted(combs,key=lambda x:x[0]):
    nodes[child].value += nodes[parent].value
  
  lst = sorted(nodes.values(),key=lambda x:x.name)
  print(" ".join([str(node.value) for node in lst]))



if __name__ == "__main__":
  main()

Submission status: Wrong Answer

Solution code:

class Node(object):
  def __init__(self,name):
    self.name = name
    self.value = 0

def main():
  N,Q = map(int,input().split())
  nodes = {}
  combs = []
  tasks = []

  for _ in range(N-1):
    parent,child = map(int,input().split())
    nodes.update({parent:Node(parent)})
    nodes.update({child:Node(child)})
    combs.append((parent,child))
  
  for _ in range(Q):
    node_name,value = map(int,input().split())
    tasks.append((node_name,value))
  
  for node_name,value in tasks:
    node = nodes[node_name]
    node.value += value

  for parent,child in combs:
    nodes[child].value += nodes[parent].value
  
  lst = sorted(nodes.values(),key=lambda x:x.name)
  print(" ".join([str(node.value) for node in lst]))



if __name__ == "__main__":
  main()

Submission status: Wrong Answer

Solution code:
import pprint
import sys
sys.setrecursionlimit(4100000)

def comp(s, l):
    ans = set(s)
    l2 = s
    for i in l2:
        if i != 0:
            ans = ans | comp(l[i], l)
    return ans


def solve():
    n, q = map(int, input().split())
    l = [[0] for i in range(n+1)]
    ans = [0]*(n+1)
    for i in range(n-1):
        a, b = map(int, input().split())
        l[a].append(b)
    for i in range(q):
        num, point = map(int, input().split())
        li = list(comp(l[num], l))
        li.append(num)
        li = list(set(li))
        for j in li:
            ans[j] += point
    ans2 = list(map(str, ans))
    ans3 = ' '.join(ans2[1::])
    print(ans3)


if __name__=="__main__":
    solve()

Submission status: Wrong Answer

Solution code:

class Node(object):
  def __init__(self,name):
    self.name=name
    self.value = 0
    self.true_value = 0
    self.nodes_names = []
    self.nodes = []
  
  def set_nodes(self,all_Nodes_dic):
    for name,node in all_Nodes_dic.items():
      if name in self.nodes_names:
        self.nodes.append(node)
  
  def update_value(self):
    for node in self.nodes:
      node.value += self.value


def main():
  N,Q = map(int,input().split())
  all_Nodes = {}
  tasks=[]
  for _ in range(N-1):
    name,pname = map(int,input().split())
    if name not in all_Nodes.keys():
      node = Node(name)
      node.nodes_names.append(pname)
      all_Nodes.update({name:node})
    else:
      node = all_Nodes[name]
      node.nodes_names.append(pname)
    
    if pname not in all_Nodes.keys():
      node = Node(pname)
      all_Nodes.update({pname:node})
  
  for _ in range(Q):
    node_name,point = map(int,input().split())
    tasks.append((node_name,point))

  for node in all_Nodes.values():
    node.set_nodes(all_Nodes)
  
  for name,value in tasks:
    parent = all_Nodes[name]
    parent.value+=value
  
  for node in all_Nodes.values():
    node.update_value()
  
  sorted_lst = sorted(list(all_Nodes.values()), key=lambda x:x.name)

  print(" ".join([str(node.value) for node in sorted_lst]))
  return


if __name__ == "__main__":
  main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
n,q = map(int,input().split())
v = defaultdict(list)
ans = [0]*n
for _ in range(n-1):
    a,b = map(int,input().split())
    v[a].append(b)
for _ in range(q):
    p,x = map(int,input().split())
    ans[p-1] += x
tmp = [1]
while tmp:
    current = tmp.pop()
    for i in v[current]:
        ans[i-1] += ans[current-1]
    tmp.extend(v[current])
print(*ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(500000)
n,q=map(int,input().split())
edge=[[] for i in range(n)]
cost=[0]*n
for i in range(n-1):
  p,s=map(int,input().split())
  p-=1;s-=1
  edge[p].append(s)
for i in range(q):
  x,c=map(int,input().split())
  x-=1
  cost[x]+=c
for i in range(n):
  for j in edge[i]:
    cost[j]+=cost[i]
for i in range(n):
  cost[i]=str(cost[i])
print(" ".join(cost))

Submission status: Wrong Answer

Solution code:
from collections import deque
n, q = [int(i) for i in input().split()]
g = [[] for i in range(n)]
 
for i in range(n-1):
    a, b = [int(_) for _ in input().split()]
    g[a-1].append(b)
c = [0 for i in range(n)]
for i in range(q):
    p, x = [int(_) for _ in input().split()]
    c[p-1] += x
 
q = deque([[1, c[0]]])
while len(q) != 0:
    p = q.popleft()
    for i in g[p[0]-1]:
        c[i-1] += p[1]
        q.append([i, c[i-1]])
 
print(*c)

Submission status: Wrong Answer

Solution code:

class Node(object):
  def __init__(self,name):
    self.name=name
    self.value = 0
    self.true_value = 0
    self.nodes_names = []
    self.nodes = []
  
  def set_nodes(self,all_Nodes_dic):
    for name,node in all_Nodes_dic.items():
      if name in self.nodes_names:
        self.nodes.append(node)
  
  def update_value(self,parent_name,val):
    for node in self.nodes:
      if parent_name != node.name:
        node.true_value += val
      node.update_value(parent_name,val)

  def get_true_value(self):
    return self.true_value+self.value


def main():
  N,Q = map(int,input().split())
  all_Nodes = {}
  tasks=[]
  for _ in range(N-1):
    name,pname = map(int,input().split())
    if name not in all_Nodes.keys():
      node = Node(name)
      node.nodes_names.append(pname)
      all_Nodes.update({name:node})
    else:
      node = all_Nodes[name]
      node.nodes_names.append(pname)
    
    if pname not in all_Nodes.keys():
      node = Node(pname)
      all_Nodes.update({pname:node})
  
  for _ in range(Q):
    node_name,point = map(int,input().split())
    tasks.append((node_name,point))

  for node in all_Nodes.values():
    node.set_nodes(all_Nodes)
  
  for name,value in tasks:
    parent = all_Nodes[name]
    parent.value+=value
  
  for node in all_Nodes.values():
    node.update_value(node.name,node.value)
  
  sorted_lst = sorted(list(all_Nodes.values()), key=lambda x:x.name)

  print(" ".join([str(node.get_true_value()) for node in sorted_lst]))
  return


if __name__ == "__main__":
  main()

Submission status: Wrong Answer

Solution code:
from collections import deque

n, q = map(int, input().split( ))
Edg=[[] for i in range(n+1)]
##
Err=10000000
Parent=[Err for i in range(n+1)]
##
##
for i in range(n-1):
    a, b = map(int, input().split( ))
    Edg[a].append(b)
    Parent[b]=a
Ans=[0 for i in range(n+1)]
P = [0 for i in range(n+1)]
##修正版



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

root=1
while Parent[root]!=Err:
    root=Parent[root]

Task=deque()
Chld=[[] for i in range(n+1)]
Task.append(root)
while len(Task)>0:
    p_=Task.popleft()
    tmp = P[p_]
    Ans[p_]+=tmp
    for child in Edg[p_]:
        Task.append(child)
        P[child]+=tmp
print(*Ans[1:])

Submission status: Wrong Answer

Solution code:
from collections import deque

n, q = map(int, input().split( ))
Edg=[[] for i in range(n+1)]
##
Err=10000000
Parent=[Err for i in range(n+1)]
##
##
for i in range(n-1):
    a, b = map(int, input().split( ))
    Edg[a].append(b)
    Parent[b]=a
Ans=[0 for i in range(n+1)]
P = [0 for i in range(n+1)]




for i in range(q):
    p, x = map(int, input().split( ))
    P[p]+=x
print(*P)
root=1
while Parent[root]!=Err:
    root=Parent[root]


Task=deque()
Chld=[[] for i in range(n+1)]
Task.append(root)
while len(Task)>0:
    p_=Task.popleft()
    tmp = P[p_]
    Ans[p_]+=tmp
    for child in Edg[p_]:
        Task.append(child)
        P[child]+=tmp
        print(*Ans)

print(*Ans[1:])

Submission status: Wrong Answer

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

ans = N * [0]

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

for com in command:
    ans[com[0]-1] += com[1]

for num in nums:
    ans[num[1]-1] += ans[num[0]-1]

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

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 9)
from bisect import bisect, bisect_left

# class Node:
#     def __init__(self, idx):
#         self.idx = idx
#         self.v = 0
#         self.parent = None
#         # self.children = []
#
#     def make_tree(self, addval=0):
#         self.v += addval
#         keyidx = bisect_left(brs_keys, self.idx)
#         while keyidx < len(brs_keys) and brs_keys[keyidx] == self.idx:
#             ni = brs[keyidx][1]
#             node = nodes[ni]
#             # if not node.children:
#             #     self.children.append(node)
#             node.make_tree(self.v)
#             keyidx += 1
#         # for c in self.children:
#         #     c.make_tree(self.v)
#
#     def __str__(self):
#         return str(self.idx)


N, Q = [int(_) for _ in input().split()]
nodes = [0] * N

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

brs.sort()
brs_keys = [b[0] for b in brs]

# for n in nodes:
#     print(n.idx, [str(c) for c in n.children])

for i in range(Q):
    p, x = [int(_) for _ in input().split()]
    nodes[p - 1] += x
    # nodes[p - 1].add(x)


# nodes[0].make_tree()


def tree(node_idx, addval):
    nodes[node_idx] += addval
    keyidx = bisect_left(brs_keys, node_idx)
    while keyidx < len(brs_keys) and brs_keys[keyidx] == node_idx:
        ni = brs[keyidx][1]
        tree(ni, nodes[node_idx])
        keyidx += 1
    # for c in self.children:
    #     c.make_tree(self.v)


tree(0, 0)

print(*[n for n in nodes])

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10**9)

def dfs(now, prev):
    ans[now]+=(h[now]+ans[prev])
    # 今いる頂点から行ける頂点を順に next に入れてループ
    for next in g[now]:
        if next != prev:
            if memo[next]==True:
                # 過去に訪れていれば終わらせる
                return False
            else:
                memo[next] = True
                dfs(next, now)


n, q = map(int, input().split())
g = [[] * n for i in range(n)]
for i in range(n-1):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    g[u].append(v)
    g[v].append(u)

Submission status: Wrong Answer

Solution code:
n, q = map(int, input().split())
ki = [0]*(n+1)
for i in range(n-1):
  a, b = map(int, input().split())
  ki[b] = a
 
c = [0]*(n+1)
for i in range(q):
  p, x = map(int, input().split())
  c[p] += x
 
for i in range(1, n+1):
  c[i] += c[ki[i]]
 
print(" ".join(map(str, c[1:])))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
n,q = map(int,input().split())
v = defaultdict(list)
ans = [0]*n
for i in range(n-1):
    a,b = map(int,input().split())
    v[a].append(b)
for _ in range(q):
    p,x = map(int,input().split())
    tmp = v[p][:]
    ans[p-1] += x
    while tmp:
        idx = tmp.pop(0)
        ans[idx-1] += x
        tmp.extend(v[idx])
print(*ans)

Submission status: Wrong Answer

Solution code:
MAX = 200005
G = [[] for i in range(MAX)]
adds = [0] * MAX
ans = [0] * MAX

# def dfs(c, p, count):
#     count += adds[c]
#     ans[c] += count
#     for i in range(len(G[c])):
#         if (G[c][i] != p):
#             dfs(G[c][i], c, count)

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

# dfs(0, -1, 0)
stack = [(0, -1, adds[0])]
while len(stack) != 0:
    cur, par, count = stack.pop()
    ans[cur] += count
    for i in range(len(G[cur])):
        if G[cur][i] != par:
            stack.append((G[cur][i], cur, count + adds[G[cur][i]]))
            
for i in range(n):
    print(ans[i])

Submission status: Wrong Answer

Solution code:

import sys
sys.setrecursionlimit(1000000)

from collections import defaultdict

def extract_tree(tree, i, memo):
    if memo[i] != []:
        return memo[i]

    if tree[i] == -1:
        return [[], memo]

    children = []
    for child in tree[i]:
        children.append(child)
        [tmp, memo] = extract_tree(tree, child, memo)
        if tmp != []:
            # flatten
            for x in tmp:
                children.append(x)

    memo[i] = children
    return [children, memo]

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

tree = [-1] * (N+1)
point = [0] * (N+1)

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

memo = defaultdict(list)
[_, memo] = extract_tree(tree, 1, memo)

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

# 面倒なので、1-index にして、最後に pop(0)することで辻褄を合わせる
for p, x in dd.items():
    point[p] += x

    if memo[p] != []:
        for i in memo[p]:
            point[i] += x


point.pop(0)
print(*point)

Submission status: Wrong Answer

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

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

op = {i: 0 for i in range(1, n+1)}
for i in range(q):
    p, x = map(int, input().split())
    op[p] = op[p] + x

res = []
for node in op.keys():
    cnt = op[node]
    res.append(cnt)
    if node in tree:
        for i in tree[node]:
            op[i] += cnt

print(*res)

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline
n,q=map(int,input().split())
l=[]
for i in range(n-1):
  l.append(list(map(int,input().split())))
l2=[]
for i in range(q):
  l2.append(list(map(int,input().split())))
connection=[]
for i in range(n):
  connection.append([])
for i in range(n-1):
  connection[l[i][0]-1].append(l[i][1]-1)
 
L4=[0]*n
for i in range(q):
  L4[l2[i][0]-1]+=l2[i][1]
distance=[0]*n
distance[0]=L4[0]

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

Submission status: Wrong Answer

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools, os, pdb
sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def _I(): return int(sys.stdin.readline())
def _F(): return float(sys.stdin.readline())
def _pf(s): return print(s, flush=True)
def perr(s): return print(s, file=sys.stderr)

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

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


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

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

"""
根からスタートするとは？

"""
def dfs():
    pass



for a, b in AB:
    if b not in d.keys():
        d[b] = 0
    if a not in d.keys():
        d[a] = 0
    d[b] += d[a]
for i in range(1, N+1):
    print(d[i], end=' ')

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

tree_data = sorted(tree_data)

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:

import sys
sys.setrecursionlimit(1000000)

from collections import defaultdict

def extract_tree(tree, i, memo):
    if memo[i] != []:
        return memo[i]

    if tree[i] == -1:
        return [[], memo]

    children = []
    for child in tree[i]:
        children.append(child)
        [tmp, memo] = extract_tree(tree, child, memo)
        if tmp != []:
            # flatten
            for x in tmp:
                children.append(x)

    memo[i] = children
    return [children, memo]

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

tree = [-1] * (N+1)
point = [0] * (N+1)

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

memo = defaultdict(list)
[_, memo] = extract_tree(tree, 1, memo)

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

# 面倒なので、1-index にして、最後に pop(0)することで辻褄を合わせる
for p, x in dd.items():
    point[p] += x

    if memo[p] != []:
        for i in memo[p]:
            point[i] += x


point.pop(0)
print(*point)

Submission status: Wrong Answer

Solution code:

N,Q = map(int,input().split())
edges = []
for n in range(N-1):
	a,b = map(int,input().split())
	edges.append((a-1,b-1))
edges.sort()

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

for a,b in edges:
	counters[b] += counters[a]

for n in range(N):
	print('{} '.format(counters[n]),end='')

Submission status: Wrong Answer

Solution code:

N,Q = map(int,input().split())
edges = []
for n in range(N-1):
	a,b = map(int,input().split())
	edges.append((a-1,b-1))
#edges.sort()

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

for a,b in edges:
	counters[b] += counters[a]

for n in range(N):
	print('{} '.format(counters[n]),end='')

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
#ABC138 D

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n,q = LI()
g = [[] for _ in range(n)]
for _ in range(n-1):
    a,b = LI()
    g[a-1].append(b-1)
for i in range(n):
    g[i].append(i)
ans = [0]*n
que = deque()
for _ in range(q):
    p,x = LI()
    que.append(p-1)
    check = [True]*n
    while que:
        v = que.pop()
        for i in g[v]:
            if check[i]:
                check[i] = False
                que.append(i)
                ans[i] += x
print(*ans)

Submission status: Wrong Answer

Solution code:
#
# Yet I'm feeling like
# 	There is no better place than right by your side
# 		I had a little taste
# 			And I'll only spoil the party anyway
# 				'Cause all the girls are looking fine
# 					But you're the only one on my mind


import sys
#import re
# inf = float("inf")
sys.setrecursionlimit(10000000)

# abc='abcdefghijklmnopqrstuvwxyz'
# abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
# mod,MOD=1000000007,998244353
# vow=['a','e','i','o','u']
# dx,dy=[-1,1,0,0],[0,0,1,-1]

# from cmath import sqrt
from collections import deque, Counter, OrderedDict,defaultdict
from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
# from math import ceil,floor,log,sqrt,factorial,pow,pi,gcd,log10,atan,tan
# from bisect import bisect_left,bisect_right
# import numpy as np

def dfs(curr,parent):
    visited[curr]=True
    value[curr]+=value[parent]
    for i in mydict[curr]:
        if not visited[i]:
            dfs(i,curr)


def get_array(): return list(map(int , sys.stdin.readline().strip().split()))
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def input(): return sys.stdin.readline().strip()

n,q=get_ints()
mydict=defaultdict(list)
parent=[0]*(n+1)
for i in range(n-1):
    a,b=get_ints()
    mydict[a].append(b)
    parent[b]=a

value=[0]*(n+1)
while q>0:
    index,score=get_ints()
    value[index]+=score
    q-=1

visited=[False]*(n+1)
dfs(1,0)

print(*value[1:])

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque, defaultdict
import copy
import bisect
input=sys.stdin.readline
#sys.setrecursionlimit(10 ** 9)
import math
import heapq
 
 
N, Q = list(map(int, input().split()))
 
for i in range(N - 1):
	a, b = list(map(int, input().split()))
 
for i in range(Q):
	p, x = list(map(int, input().split()))

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque, defaultdict
import copy
import bisect
#input=sys.stdin.readline
#sys.setrecursionlimit(10 ** 9)
import math
import heapq
 
for i in range(200000):
	print(i*10000, end = "")
	print(" ", end = "")
print(0)

Submission status: Wrong Answer

Solution code:

import sys
from collections import deque, defaultdict
import copy
import bisect
#input=sys.stdin.readline
#sys.setrecursionlimit(10 ** 9)
import math
import heapq


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

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


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

Submission status: Wrong Answer

Solution code:
n,q,*t=map(int,open(0).read().split())

e=[[]for _ in[0]*n]
s=[0]
d=s*n#入力時点での各ノードに加算する数字の合計を保持[20,0,0,0,0,0]
f=[1]+s*n
for a,b in zip(*[iter(t[:-q-q])]*2):#入力Tの配列のqまでを2つのリストにして回す。
  print(a,b)
  e[a-1]+=b-1,#eリストにリンクの情報を保持
  e[b-1]+=a-1,
  print(e)
for p,x in zip(*[iter(t[-q-q:])]*2):d[p-1]+=x
print('D',d)
while s:
  v=s.pop()
  for w in e[v]:
    if f[w]:continue#１なら飛ばす
    f[w]=1
    d[w]+=d[v]
    print('S',s)
    print('F',f)
    print('D',d)
    s+=w,
print(*d)

Submission status: Wrong Answer

Solution code:

import sys
sys.setrecursionlimit(1000000)

from collections import defaultdict

def extract_tree(tree, i, memo):
    if tree[i] == -1:
        return [[], memo]

    children = []
    for child in tree[i]:
        children.append(child)
        [tmp, memo] = extract_tree(tree, child, memo)
        if tmp != []:
            # flatten
            for x in tmp:
                children.append(x)

    memo[i] = children
    return [children, memo]

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

tree = [-1] * (N+1)
point = [0] * (N+1)

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

memo = defaultdict(list)
[_, memo] = extract_tree(tree, 1, memo)

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

# 面倒なので、1-index にして、最後に pop(0)することで辻褄を合わせる
for p, x in dd.items():
    point[p] += x

    if memo[p] != []:
        for i in memo[p]:
            point[i] += x


point.pop(0)
print(*point)

Submission status: Wrong Answer

Solution code:

import sys
from collections import deque, defaultdict
import copy
import bisect
#input=sys.stdin.readline
#sys.setrecursionlimit(10 ** 9)
import math
import heapq


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

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

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

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
 
n, q = map(int, input().split())
g = [[] for _ 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)
 
ans = [0]*n  
for j in range(q):
  p, x = map(int, input().split())
  ans[p-1] += x
  
from collections import deque
s = deque()
s.append(0)
 
while s:
  v = s.pop()
  for v_ in g[v]:
    ans[v_] += ans[v]
    s.append(v_)
 
print(' '.join(map(str, ans)))