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 = list(map(int,input().split()))

graph = [[] for i in range(n)]
for i in range(n-1):
    a,b = list(map(int,input().split()))
    graph[a-1].append(b-1)
    graph[b-1].append(a-1)
cost_ls = [0 for i in range(n)]
for i in range(q):
    a,b = list(map(int,input().split()))
    cost_ls[a-1] += b

#深さ優先探索
checkls = [True for i in range(n)]
kesita = [True for i in range(n)]
v = 0
cost = 0
stack = [0]
checkls[0] = False
hikuV = []
ansls = [0 for i in range(n)]
while stack:
    v = stack.pop()
    cost += cost_ls[v]
    hikuV.append(v)
    checkls[v] = False
    ansls[v] = cost
    finish_check = True
    for i in graph[v]:
        if checkls[i]:
            stack.append(i)
            finish_check = False
    if not stack:
        break
    if finish_check:
        cost -= cost_ls[v]
        while True:
            breakcheck = False
            kari = 0
            for i in graph[v]:
                if v != i and kesita[i]:
                    kari = i
                if checkls[i]:
                    breakcheck = True
                    break
            if breakcheck:
                break
            cost -= cost_ls[v]
            kesita[v] = False
            v = kari

for i in range(len(ansls)):
    print(ansls[i],end = ' ')
print()

Submission status: Wrong Answer

Solution code:
from collections import deque

n,q = map(int,input().split())
graph = [[] for _ in range(n)]
connect = [[_] for _ in range(n)]
cnt = [0] * n
imos = [0] * (n+1)

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

for i in range(n):
    que = deque(graph[i])
    while que:
        c = que.popleft()
        if c > i:
            connect[i].append(c)
            for j in graph[c]:
                if j > i and j not in connect[i]:
                    que.append(j)


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

for i in range(n):
    if i==0:
        cnt[i] = imos[i]
    else:
        cnt[i] = imos[i] + cnt[i-1]

print(str(cnt).replace('[','').replace(']','').replace(',',''))

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  
  tree[tree_parent[a]].append(b)
    
for i in range(Q):
  p, x = map(int, input().split())
  for node in tree[p]:
    points[node-1] += x
    
for point in points:
  print(point, end=" ")

Submission status: Wrong Answer

Solution code:
n,q=map(int,input().split())
lisn=[]
lisq=[]
for i in range(n-1):
    lisn.append(list(map(int,input().split())))
lisn.sort()
for i in range(q):
    lisq.append(list(map(int,input().split())))
ans=[]
for i in range(n):
    ans.append(0)

for i in range(q):
    for j in range(n-1):
        if lisn[j][0]==lisq[i][0]:
            ans[(lisn[j][0]-1)]+=lisq[i][1]
            ans[(lisn[j][1]-1)]+=lisq[i][1]
            a=0
            while a!=n-2-j:
                a=0
                for k in range(n-2-j):
                    if lisn[n-2-k][0]==lisn[j][1]:
                        ans[(lisn[n-2-k][0]-1)]+=lisq[i][1]
                        ans[(lisn[n-2-k][1]-1)]+=lisq[i][1]
                    else:
                        a+=1

print(*ans)

Submission status: Wrong Answer

Solution code:
N, Q = map(int, input().split())
AB = []
for _ in range(N - 1):
    a, b = map(int, input().split())
    AB.append((a, b))
PX = [0] * (N + 1)
for _ in range(Q):
    p, x = map(int, input().split())
    PX[p] += x
ans = [0] * (N + 1)
p = [False] * (N + 1)
for a, b in AB:
    if PX[a] > 0 and p[a] is False:
        ans[a] += PX[a]
        p[a] = True
    ans[b] += ans[a]
    if PX[b] > 0 and p[b] is False:
        ans[b] += PX[b]
        p[b] = True
print(' '.join(map(str, ans[1:])))

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline
import collections
import bisect
import fractions
#sys.stdin=file('input.txt')
#sys.stdout=file('output.txt','w')
mod=1000000007
pi=3.1415926535897932
IS=float('inf')
xy=[(1,0),(-1,0),(0,1),(0,-1)]
bs=[(-1,-1),(-1,1),(1,1),(1,-1)]
def niten(a,b): return abs(a-b) if a>=0 and b>=0 else  a+abs(b) if a>=0 else abs(a)+b if b>=0 else abs(abs(a)-abs(b))
def fib(n): return [(seq.append(seq[i-2] + seq[i-1]), seq[i-2])[1] for seq in [[0, 1]] for i in range(2, n)]
# fractions.gcd(x,y)
def lcm(a,b): return a*b//fractions.gcd(a,b)
def eof(t): print(t); exit()

def qul(d,l,p):
    if p in d:
        for j in d[p]:
            if j in d:
                if j not in l:
                    l.append(j)
                qul(d,l,j)
            else:
                l.append(j)
def sol():
    d={}
    n,q=map(int,input().split())
    for i in range(n-1):
        a,b=map(int,input().split())
        if a in d:
            d[a].append(b)
        else:
            d[a]=[b]
    w=[0]*(n+1)
    for i in d:
        d[i].sort(reverse=True)
    for i in range(q):
        p,x=map(int,input().split())
        w[p]+=x
    for i in range(n,0,-1):
        l=[]
        qul(d,l,i)
        for j in l:
            w[j]+=w[i]
        #print(i,l)
    print(*w[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)]
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]
    if parent==[]:
      break
    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:
from collections import defaultdict, deque

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

for i in range(n - 1):
    ai, bi = map(int, input().split())
    edge[ai].append(bi)
    edge[bi].append(ai)

ops = []
for i in range(q):
    pp, xx = map(int, input().split())
    ops.append((pp, xx))


def get_parent():
    dq = deque()
    dq.append(1)
    visited = set()
    parent = {1: None}
    while True:
        if len(dq) == 0:
            break
        p = dq.popleft()
        visited.add(p)
        for c in edge[p]:
            if c in visited:
                continue
            parent[c] = p
            dq.append(c)
    return parent


def get_all_children(parent):
    all_children = defaultdict(set)
    dq = deque()
    visited = set()
    leaf = set(range(1, n + 1)) - set(parent.values())
    for l in leaf:
        dq.append(l)

    while True:
        if len(dq) == 0:
            break
        i = dq.popleft()
        if i in visited:
            continue
        all_children[i].add(i)
        p = parent[i]
        if p is None:
            continue
        all_children[p].update(all_children[i])
        dq.append(p)
    return all_children


if __name__ == '__main__':
    parent = get_parent()
    all_children = get_all_children(parent)

    counter = defaultdict(int)
    for p, x in ops:
        for parent in all_children[p]:
            counter[parent] += x
    print(' '.join([str(counter[i]) for i in sorted(counter.keys())]))

Submission status: Wrong Answer

Solution code:
n,q = map(int,input().split())
a = []
b = []
p = []
x = []
for i in range(n-1):
    a1,b1=[int(i) for i in input().split()]
    a.append(a1)
    b.append(b1)
for i in range(q):
    p1,x1=[int(i) for i in input().split()]
    p.append(p1)
    x.append(x1)
cnt = [0]*n
root = [0]*n
for i in range(q):
    cnt[p[i]-1] += x[i]
    for j in range(n-1):
        if a[j] == p[i]:
            cnt[b[j]-1] += x[i]
            root[j] = b[j]
        if a[j] in root:
            cnt[b[j]-1] += x[i]
            root[j] = b[j]
    root = [0]*n
print(cnt)

Submission status: Wrong Answer

Solution code:
a=[]
b=[]
c=[]
s=""
for x in input().split(" "):
    c.append(int(x))
i=0
il=[]
while i<c[0]-1:
    for x in input().split(" "):
        il.append(int(x))
    a.append(il)
    i+=1
    s=""
    il=[]
i=0
while i<c[1]:
    for x in input().split(" "):
        il.append(int(x))
    b.append(il)
    i+=1
    s=""
    il=[]

k=[]
kp=[]
kps=[]
bb=[]
i=0
while i<=c[0]:
    k.append([])
    kp.append(0)
    bb.append(0)
    i+=1
for x in a:
    k[x[0]].append(x[1])
for x in b:
    bb[x[0]]+=x[1]
b=[]
i=0
for x in bb:
    b.append([i,x])
    i+=1
i=0
il=[]
for x in b:
    while i<c[0]:
        if i==x[0]:
            il.append(i)
            kp[i]+=x[1]
        if i>=x[0] and i in il:
            for y in k[i]:
                il.append(y)
                kp[y]+=x[1]
        i+=1
    i=0
    il=[]
del kp[0]
for x in kp:
    kps.append(str(x))
print(' '.join(kps))

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[t] = 0

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

Submission status: Wrong Answer

Solution code:
N,Q = list(map(int, input().split(" ")))
v_list = [0 for _ in range(N)] # n-1でやること注意
dic_tree = {}
for i in range(N):
    dic_tree[i+1] = [] 

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

# make tree
for k in reversed(range(N)):
    if len(dic_tree) == 0:
        continue
    
    for node in dic_tree[k+1]:
        dic_tree[k+1].extend(dic_tree[node])
        
# add 1 
dic_tree[1].append(1)
    
for i in range(Q):
    p, x = list(map(int, input().split(" ")))
    
    for i in dic_tree[p]:
        v_list[i-1] += x

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

Submission status: Wrong Answer

Solution code:
from queue import Queue

n , q = map(int, input().split())
lab = []
points = [0]*n
for i in range(n-1):
    lab.append(list(map(int, input().split())))
lpx = []
for i in range(q):
    lpx.append(list(map(int, input().split())))

lll = []
for i in range(n):
    childs = Queue()
    inc = []
    parent = i+1
    childs.put(parent)
    while childs.qsize() > 0:
        a = childs.get()
        inc.append(a)
        for k in lab:
            if k[0] == a:
                childs.put(k[1])
    lll.append(list(set(inc)))

print(lll)

for i in lpx:
    print(i[0]-1)
    for j in lll[i[0]-1]:
        points[j-1] += i[1]
print(' '.join(map(str, points)))

Submission status: Wrong Answer

Solution code:
#import numpy as np
#from numpy import*
#from scipy.sparse.csgraph import shortest_path #shortest_path(csgraph=graph) # dijkstra# floyd_warshall
#from scipy.sparse import csr_matrix

from collections import* #defaultdict Counter deque appendleft
from fractions import gcd
from functools import* #reduce
from itertools import* #permutations("AB",repeat=2) combinations("AB",2) product("AB",2) groupby accumulate
from operator import mul,itemgetter
from bisect import* #bisect_left bisect_right
from heapq import* #heapify heappop heappushpop
from math import factorial,pi
from copy import deepcopy
import sys
sys.setrecursionlimit(10**8)
#input=sys.stdin.readline  #危険！基本オフにしろ！
 
n,q=map(int,input().split())
d=defaultdict(list)
parent=defaultdict(int)
for i in range(n-1):
    a,b=map(int,input().split())
    d[a].append(b)
def DFS(point,d,s):
    for i in d[point]:
        if len(d[i])==0:
            parent[i]+=s
        else:
            parent[i]+=s
            DFS(i,d,s)
            

ans=0
for i in range(q):
    a,b=map(int,input().split())
    if a==1:
        parent[a]+=b
    DFS(a,d,b)
print(*[v for k,v in sorted(parent.items())])

Submission status: Wrong Answer

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


tree=[[]]
result=[0]

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

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


  
for _ in range(q):
  no,value=map(int,input().split())
  result[no-1]+=value
  for j in tree[no-1]:
    result[j-1]+=value
  
print(*result)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
def main():

    N, Q = [int(x) for x in input().split()]
    counter = {key:0 for key in range(1, N+1)}
    parent_dict = dict()
    child_data = defaultdict(list)
    child_data[1] = [1]

    # 要は木構造っぽいものを作りたいが、再起関数だと処理時間で死んだ
    # なので、親一覧 + 自分のリストを作成する
    for _ in range(N - 1):
        a, b = [int(x) for x in input().split()]
        parent_dict[b] = a
        child_data[b].append(b)
        temp = b
        while temp in parent_dict:
            temp = parent_dict[temp]
            child_data[temp].append(b)
    
    print(parent_dict)
    print(child_data)

    # 親一覧 + 自分のリストから答えを出す   
    for _ in range(Q):
        p, x = [int(x) for x in input().split()]
        for key in child_data[p]:
            counter[key] += x

    print(" ".join([str(val) for key, val in sorted(counter.items())]))

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
class Node:
  def __init__(self):
    self.counter = 0
    self.childs = []
    self.parents = set()
  def add_child(self, node):
    self.childs.append(node)
  def add_parents(self, node):
    self.parents.add(node)
 
N, Q = [int(i) for i in input().split()]
ndic = {}
for i in range(1, N+1):
  ndic[i] = Node()
  ndic[i].add_child(ndic[i])
for i in range(N-1):
  a, b = [int(i) for i in input().split()]
  ndic[a].add_child(ndic[b])
  ndic[b].add_parents(ndic[a])
  for n in ndic[a].parents:
    n.add_child(ndic[b])  
    ndic[b].add_parents(n)

Submission status: Wrong Answer

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

counter = [0] * N #葉に加算される値を格納
weed = [[0 for i in range(N)] for j in range(N)] # 葉の値を格納
for i in range(0,N):
    weed[i][i]=1
# 葉同士のひも付きを先に計算する
#print(weed)
for i in range(N-1):
    #print(a[i])
    #print(b[i])
    weed[a[i]-1][b[i]-1] = 1
for i in range(N-1):
    for j in range(N-1):
        if weed[i][j] != 0:
            weed[i] = [x+y for (x,y) in zip(weed[i],weed[j])]
#print(weed)
# カウンターを計算する
for q in range(Q):
    for i in range(N):
        # print("p[q]"+str(p[q]))
        if weed[p[q]-1][i] > 0:
            counter[i] += x[q]
print(counter)

Submission status: Wrong Answer

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

a = {}
b = {}
input_dict = {}
for n in range(1, N):
    input_a, input_b = map(str, input().split())
    input_dict.setdefault(input_b, [])
    input_dict[input_b].extend([input_a, input_b])
    if input_a in input_dict:
        input_dict[input_b].extend(input_dict[input_a])
    input_dict[input_b] = list(set(input_dict[input_b]))

tree = {}
for k, v in input_dict.items():
    for value in v:
        tree.setdefault(value, [])
        tree[value].append(k)
tree["1"].append("1")

ans = {}
for q in range(0, Q):
    input_p, input_x = map(int, input().split())
    for d in tree[str(input_p)]:
        ans.setdefault(d, 0)
        ans[d] += input_x

sorted_ans = sorted(ans.items(), key=lambda x: x[0][0])

ans_list = []
for sa in sorted_ans:
    ans_list.append(sa[1])

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

Submission status: Wrong Answer

Solution code:
import sys
import collections


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

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

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

    def rec_add(node, cur, c):
        if c > 1000:
            return
        cur += adds[node]
        results[node] = cur
        seen.add(node)
        for child in tree[node]:
            if child in seen:
                continue
            rec_add(child, cur, c+1)

    rec_add(0, 0, 0)
    print(' '.join([str(n) for n in results]))


main()

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(tree)
    
for point in points:
  print(point, end=" ")

Submission status: Wrong Answer

Solution code:
from collections import deque

n,q = map(int,input().split())
graph = [[] for _ in range(n)]
connect = [[_] for _ in range(n)]
cnt = [0] * n
imos = [0] * (n+1)

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

for i in range(n):
    que = deque(graph[i])
    while que:
        c = que.popleft()
        if c > i:
            connect[i].append(c)
            que += deque(graph[c])

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

for i in range(n):
    if i==0:
        cnt[i] = imos[i]
    else:
        cnt[i] = imos[i] + cnt[i-1]

print(str(cnt).replace('[','').replace(']','').replace(',',''))

Submission status: Wrong Answer

Solution code:
import numpy as np

num_node, num_query = map(int, input().split())
node_info = [map(int, input().split()) for i in range(num_node-1)]
query_info = [map(int, input().split()) for i in range(num_query)]

numpy_layer = np.zeros(num_node)
numpy_size = np.zeros(num_node)
numpy_layer[0] = 1

for node in node_info:
    a1, b1 = node
    print(a1, b1)
    a1_layer = numpy_layer[int(a1)-1]
    numpy_layer[int(b1)-1] = a1_layer + 1

for query in query_info:
    node, size = query
    node_size = int(numpy_layer[node-1])
    numpy_size[node-1] += size
    # 根を探す
    #np.where(numpy_layer > node_size, numpy_size + size, numpy_size)
    numpy_size[np.where(numpy_layer > node_size)] += size

numpy_size = numpy_size.astype("int64")
print(*numpy_size)

Submission status: Wrong Answer

Solution code:
N, Q = list(map(int,input().rstrip().split(' ')))
sum = [0]*N
connected = list()
from functools import lru_cache

for _ in range(N-1):
    connected.append(list(map(int,input().rstrip().split(' '))))

@lru_cache(maxsize=1000)
def subtree(node):
    sub_tree_list = []
    for c in connected:
        if c[0] == node:
            sub_tree_list.append(c[1])

    if sub_tree_list == []:
        return [node]
    else:
        tmp = []
        for sub in sub_tree_list:
            tmp += subtree(sub)
        return [node] + tmp

for _ in range(Q):
    p, x = list(map(int,input().rstrip().split(' ')))
    sub = subtree(p)
    for y in sub:
        print(sum)
        print("y is :" + str(y))
        sum[y-1] += x

for r in sum:
    print(r, end=' ')

Submission status: Wrong Answer

Solution code:
n, q = map(int, input().split())
link = list()
net = dict()
counter = list([0]*n)
for i in range(n-1):
  link.append(list(map(int, input().split())))
link.reverse()
for e in link:
    if e[0]-1 in net:
        net[e[0]-1].append(e[1]-1)
    else:
        net[e[0]-1] = [e[1]-1]
    if e[1]-1 in net:
            net[e[0]-1].extend(net[e[1]-1])
  
for i in range(q):
  p,pp = map(int, input().split())
  counter[p-1] += pp
  if p-1 in net:
      for s in net[p-1]:
          counter[s] += pp

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

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 tree[p]:
    points[node-1] += x
    
# print(tree)
    
for point in points:
  print(point, end=" ")

Submission status: Wrong Answer

Solution code:
n,q = map(int,input().split())
c = [list(input().split()) for i in range(n-1)]
y = [list(input().split()) for i in range(q)]
a = list(c[j][0] for j in range(n-1))
b = list(c[j][1] for j in range(n-1))
p = list(y[j][0] for j in range(q))
x = list(y[j][1] for j in range(q))
count = [0 for i in range(n)]
for i in range(q):
    count[int(p[i])-1]+=int(x[i])
for i in range(n-1):
    count[int(b[i])-1]+=count[int(a[i])-1]
print(*count)

Submission status: Wrong Answer

Solution code:
n,q = map(int, input().split())
point_array = [list(map(int,input().split())) for i in range(n-1)]
action_array = [list(map(int,input().split())) for i in range(q)]
    
solution = [0]*n

for i in range(q):
    solution[action_array[i][0]-1] += action_array[i][1]


for i in range(n-1):
    solution[point_array[i][1]-1] += solution[point_array[i][0]-1]
    
print(*solution)

Submission status: Wrong Answer

Solution code:
N,Q = map(int,input().split())
A={}
# B={}
P=[]
X=[]
Parents=[[] for i in range(N)]
Daughters=[[]for i in range(N)]
Tree=[[]for i in range(N)]
Result=[0 for i in range(N)]
for i in range(N-1):
    a_, b_ = map(int, input().split())
    Parents[b_-1].append(a_)
    Daughters[a_-1].append(b_)
# print(A)
for i in range(N):
    Tree[i].extend([i+1])
    Tree[i].extend(Daughters[i])
    for d in Daughters[i]:
        Tree[i].extend(Daughters[d-1])

# print(Parents)
# print(Daughters)
# print(Tree)

for i in range(Q):
    p_, q_ = map(int, input().split())
    for tr in Tree[p_-1]:
        Result[tr-1]+=q_
    P.append(p_)
    X.append(q_)

print(Result)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict


def set_child(from_p) -> int:
    global effect_list
    global start_edge_list
    effect_list[from_p].add(from_p)
    if from_p not in start_edge_list:
        return effect_list[from_p]
    for edge in edge_list:
        if from_p == edge[0]:
            effect_list[from_p].add(edge[1])
            children = set_child(edge[1])
            if children:
                for j in children:
                    effect_list[from_p].add(j)
        if from_p < edge[0]:
            return effect_list[from_p]
    return effect_list[from_p]


N, Q = input().split(' ')
N = int(N)
Q = int(Q)
ab = [input().split(' ') for i in range(N - 1)]
px = [input().split(' ') for i in range(Q)]

edge_list = sorted(ab)
start_edge_list = [e[0] for e in edge_list]

effect_list = defaultdict(lambda: set())  # key: pi, value: piから影響を受ける頂点すべて
index = 0
for i in range(N):
    top_n = i + 1
    set_child(str(top_n))

result = [0 for i in range(N)]
for impact in px:
    top_n = impact[0]
    val = int(impact[1])

    if top_n in effect_list:
        for target in effect_list[top_n]:
            result[int(target) - 1] += val

print(result)

Submission status: Wrong Answer

Solution code:

NQ = input().split(' ')
N = int(NQ[0])
Q = int(NQ[1])
candidate_list = []
tree_dict = {}
#Make tree dict
for i in range(N-1):
    ab = input().split(' ')
    a = int(ab[0])
    b = int(ab[1])
    tree_dict[i+1] = {
                'count': 0,
                'has_trees': []
            }
    candidate_list.append((a,b))
tree_dict[N] = {
    'count': 0,
    'has_trees': []
    }
candidate_list.reverse()

for candidate in candidate_list:
    a = candidate[0]
    b = candidate[1]
    tree_dict[a]['has_trees'] += tree_dict[b]['has_trees'] + [b]
        

for _ in range(Q):
    px = input().split(' ')
    p = int(px[0])
    x = int(px[1])
    tree_dict[p]['count'] += x
    for num in tree_dict[p]['has_trees']:
        tree_dict[num]['count'] += x

out_put_list = []
for each_dict in tree_dict.values():
    out_put_list.append(str(each_dict['count']))
print(' '.join(out_put_list))

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():
      continue
    elif s in p.keys():
        p[t] = p[s]
    else:
        p[t] = 0

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

Submission status: Wrong Answer

Solution code:
import collections as C
n, q = map(int,input().split())

g = C.Counter([])
p = C.Counter([])

for i in range(n-1):
	a,b = map(int,input().split())
	if a not in g.keys():
		g[a] = [b]
	elif a in g.keys():
		g[a] = g[a] + [b]

for i in range(q):
	a,b = map(int,input().split())
	if a not in p.keys():
		p[a] = b
	elif a in p.keys():
		p[a] = p[a] + b

ans = [0 for _ in range(n)]
que = [0]
i = 1
for i in range(n-1):

	if i in p.keys():
		ans[i-1] += p[i]
	if i in g.keys():
		for j in g[i]:
			ans[j-1] = ans[i-1]
			que.append(j)
	i = que.pop()


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

Submission status: Wrong Answer

Solution code:
n,q = map(int, input().split())
edges = [list(map(int, input().split())) for i in range(n-1)]
counters = [0] * n
for _ in range(q):
    p, x = map(int, input().split())
    tmp_l = [p]
    for e in edges:
        if e[0] == p:
            tmp_l.append(e[1])
            for ee in edges:
                if ee[0] == e[1]:
                    tmp_l.append(ee[1])
    for i in tmp_l:
        counters[i-1] = counters[i-1] + x
print(counters)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline

##### リストの 二分木検索 #####
# bisect_left(lists, 3)
# bisect_right(lists, 3)

##### プライオリティキュー #####
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除＆その最小値を出力

# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと

##### タプルリストのソート #####
# sorted(ans) #(a, b) -> 1st : aの昇順, 2nd : bの昇順
# sorted(SP, key=lambda x:(x[0],-x[1])) #(a, b) -> 1st : aの昇順, 2nd : bの降順
# sorted(SP, key=lambda x:(-x[0],x[1])) #(a, b) -> 1st : aの降順, 2nd : bの昇順
# sorted(SP, key=lambda x:(-x[0],-x[1])) #(a, b) -> 1st : aの降順, 2nd : bの降順

# sorted(SP, key=lambda x:(x[1])) #(a, b) -> 1st : bの昇順
# sorted(SP, key=lambda x:(-x[1])) #(a, b) -> 1st : bの降順

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))

def main():
	N,Q = inputMap()
	ki = [[] for _ in range(N)]
	kiki = []
	ans = [0 for _ in range(N)]

	for i in range(N-1):
		a,b = inputMap()
		ki[a-1].append(b-1)

	ki2 = ki[::-1]
	for i,val in enumerate(ki2):
		if len(val) == 0:
			kiki.append([])
			continue
		addd = val
		for vol in val:
			print(ki[vol])
			addd.extend(ki[vol])
		kiki.append(addd)

	kiki = kiki[::-1]
	#print(kiki)
	for i in range(Q):
		p,x = inputMap()
		if p == 1:
			for i in range(N):
				ans[i] += x
		else:
			ans[p-1] += x
			for vol in kiki[p-1]:
				ans[vol] += x

	print(*ans)

if __name__ == "__main__":
	main()

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)
    dic[b].append(a)

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
        dic[to].remove(root)
    todo += children

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

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 tree[p]:
    points[node-1] += x
    
print(tree)
    
for point in points:
  print(point, end=" ")

Submission status: Wrong Answer

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

l=[]
x=0

for _ in range(n-1):
  l1=list(map(int,input().split()))
  l.append(l1)

l2=[0]*n  
for _ in range(q):
  a,b=map(int,input().split())
  l2[a-1]+=b

for i in l:
  a,b=i
  l2[b-1]+=l2[a-1]
  
ans=list(map(str,l2))
print(' '.join(ans))