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
input = sys.stdin.readline

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

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

a_s = sorted(a)
ans= [ 0 for _ in range(N)]

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

for i in range(N-1):
    ans[a_s[i][1]-1] += ans[a_s[i][0]-1]

print(*ans)

#if __main__ == "__main__":

Submission status: Wrong Answer

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

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

a_s = sorted(a)
ans= [ 0 for _ in range(N)]

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

for i in range(N-1):
    ans[a_s[i][1]-1] += ans[a_s[i][0]-1]

print(*ans)

Submission status: Wrong Answer

Solution code:
N, Q = map(int, input().split())
tree = []
ops = []
for _ in range(N-1):
    tree.append(tuple(map(int, input().split())))
for _ in range(Q):
    ops.append(tuple(map(int, input().split())))

ans = [0] * N
ops.sort(key=lambda x:x[0])

for op in ops:
    ans[op[0]-1] += op[1]-1
    
for edge in tree:
    ans[edge[1]-1] += ans[edge[0]-1]
    
print(*ans)

Submission status: Wrong Answer

Solution code:
N, Q = map(int, input().split())
tree = []
ops = []
for _ in range(N-1):
    tree.append(tuple(map(int, input().split())))
for _ in range(Q):
    ops.append(tuple(map(int, input().split())))

ans = [0] * N
ops.sort(key=lambda x:x[0])

for op in ops:
    ans[op[0]-1] += op[1]
    
for edge in tree:
    ans[edge[1]-1] += ans[edge[0]-1]
    
print(*ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

def calc_final_increases(parent, node, root, increases):
    path = [node]
    current = node

    while current in parent:
        current = parent[current]
        path.append(current)

    output = 0
    for n in path:
        output += increases[n]

    return output

n, q = [int(i) for i in input().split()]
# print 'nq', n, q
children = defaultdict(list)
parent = {}

for _ in range(n-1):
    u, v = [int(i) for i in input().split()]
    # print 'uv', u, v
    children[u].append(v)
    parent[v] = u

root = [node for node in children if node not in parent]
leaves = [node for node in parent if node not in children]

# is_child = defaultdict(lambda: defaultdict(lambda: False))
# for leaf in leaves:
#     mark_child(parent, leaf, root, is_child)

changes = defaultdict(lambda: 0)

increases = defaultdict(lambda: 0)
for _ in range(q):
    p, x = [int(i) for i in input().split()]
    increases[p] += x 

output = []
for node in range(n+1)[1:]:
    output.append(calc_final_increases(parent, node, root, increases))

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

def calc_final_increases(parent, node, root, increases):
    path = [node]
    current = node

    while current in parent:
        current = parent[current]
        path.append(current)

    output = 0
    for n in path:
        output += increases[n]

    return output

n, q = [int(i) for i in input().split()]
# print 'nq', n, q
children = defaultdict(list)
parent = {}

for _ in range(n-1):
    u, v = [int(i) for i in input().split()]
    # print 'uv', u, v
    children[u].append(v)
    parent[v] = u

root = [node for node in children if node not in parent]
leaves = [node for node in parent if node not in children]

# is_child = defaultdict(lambda: defaultdict(lambda: False))
# for leaf in leaves:
#     mark_child(parent, leaf, root, is_child)

changes = defaultdict(lambda: 0)

increases = defaultdict(lambda: 0)
for _ in range(q):
    p, x = [int(i) for i in input().split()]
    increases[p] += x 

output = []
for node in range(n+1)[1:]:
    output.append(calc_final_increases(parent, node, root, increases))

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

def calc_final_increases(parent, node, root, increases):
    path = [node]
    current = node

    while current in parent:
        current = parent[current]
        path.append(current)

    output = 0
    for n in path:
        output += increases[n]

    return output

n, q = [int(i) for i in raw_input().split()]
# print 'nq', n, q
children = defaultdict(list)
parent = {}

for _ in range(n-1):
    u, v = [int(i) for i in raw_input().split()]
    # print 'uv', u, v
    children[u].append(v)
    parent[v] = u

root = [node for node in children if node not in parent]
leaves = [node for node in parent if node not in children]

# is_child = defaultdict(lambda: defaultdict(lambda: False))
# for leaf in leaves:
#     mark_child(parent, leaf, root, is_child)

changes = defaultdict(lambda: 0)

increases = defaultdict(lambda: 0)
for _ in range(q):
    p, x = [int(i) for i in raw_input().split()]
    increases[p] += x 

output = []
for node in range(n+1)[1:]:
    output.append(calc_final_increases(parent, node, root, increases))

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

Submission status: Wrong Answer

Solution code:
# https://atcoder.jp/contests/abc138/submissions/7003326
import sys
from collections import deque
def main():
    input=sys.stdin.readline
    n,q=map(int,input().split())

    edge=[[] for _ in range(n)]
    for _ in range(n-1):
        u,v=map(int,input().split())
        u-=1;v-=1
        edge[u].append(v)
   
    cost=[0]*n
    for _ in range(q):
        p,x=map(int,input().split())
        p-=1
        cost[p]+=x

    for idx,e in enumerate(cost):
        if e==0:continue
        for f in edge[idx]:
            cost[f]+=e

    print(*cost)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

def mark_child(parent, leaf, root, is_child):
    output = [leaf]
    current = leaf

    while current in parent:
        current = parent[current]
        output.append(current)

    for i in range(len(output)):
        for j in range(i+1, len(output)):
            is_child[output[i]][output[j]] = True

n, q = [int(i) for i in raw_input().split()]
# print 'nq', n, q
children = defaultdict(list)
parent = {}

for _ in range(n-1):
    u, v = [int(i) for i in raw_input().split()]
    # print 'uv', u, v
    children[u].append(v)
    parent[v] = u

root = [node for node in children if node not in parent]
leaves = [node for node in parent if node not in children]

is_child = defaultdict(lambda: defaultdict(lambda: False))

for leaf in leaves:
    mark_child(parent, leaf, root, is_child)

changes = defaultdict(lambda: 0)

for _ in range(q):
    p, x = [int(i) for i in raw_input().split()]
    # print 'px', p, x
    for node in range(n+1):
        if is_child[node][p]:
            changes[node] += x
    changes[p] += x

output = [changes[i] for i in range(n+1)[1:]]
print ' '.join(map(str, output))

Submission status: Wrong Answer

Solution code:
N,Q=map(int,input().split())
a=[]
b=[]
for i in range(N-1):
    A,B=map(int,input().split())
    a.append(A)
    b.append(B)
p=[]
x=[]
for _ in range(Q):
    P,X=map(int,input().split())
    p.append(P)
    x.append(X)
c=[0]*N
for i in range(Q):
    c[p[i]-1]=c[p[i]-1]+x[i]
for i in range(1,N-1):
    k=i
    for j in range(i):
        if a[i-j-1]>a[k]:
            a[k],a[i-j-1]=a[i-j-1],a[k]
            b[k],b[i-j-1]=b[i-j-1],b[k]
            k=k-1
        else:
            break
for i in range(N-1):
    c[b[i]-1]=c[b[i]-1]+c[a[i]-1]
s=str(c[0])
for i in range(1,N):
    s=s+" "+str(c[i])
print(s)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(1000000000)
N, Q = map(int, input().split())

nodes = [-1 for _ in range(N)] # 親ノードを保存
counts = [0]*N
for _ in range(N-1):
    a, b = input().split()
    nodes[int(b)-1] = int(a)-1

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

for i in range(N):
    if nodes[i] == -1:
        continue
    counts[i] += counts[nodes[i]]

for count in counts:
    print(count, end=" ")

Submission status: Wrong Answer

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

p = sorted(p, key=lambda x: x[0])
K = [0] * N
for i in range(Q):
    K[x[i][0]-1] += x[i][1]
for i in range(N-1):
    K[p[i][1]-1] += K[p[i][0]-1]
print(*K)

Submission status: Wrong Answer

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

K = [0] * N
for i in range(Q):
    K[x[i][0]-1] += x[i][1]
for i in range(N-1):
    K[p[i][1]-1] += K[p[i][0]-1]
print(*K)

Submission status: Wrong Answer

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

n, q = map(int, input().split())
tree = [[] for _ in range(n)]

for _ in range(n-1):
    a, b = map(int, input().split())
    tree[a-1].append(b-1)
    
ans = [0] * n

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

query = deque([(0, -1)]) # current, parent
while query:
    current_node, parent_node = query.popleft()
    current_value = ans[current_node]
    for node in tree[current_node]:
      ans[node] += current_value
      query.append([node, current_node])

print(*ans)

Submission status: Wrong Answer

Solution code:
# Ki
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)]

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

# まずpで指定された木だけにxを足す		
for i in range(Q):
	p = px[i][0]
	x = px[i][1]
	anslist[p-1] += x 
	
# 次にpで指定された木の根全てにxを足す(その木は除く)
ab = sorted(ab) # aが小さい順にソート
for i in range(N-1):
	a = ab[i][0]
	b = ab[i][1]
	anslist[b-1] += anslist[a-1]
	
ans = ' '.join(map(str, anslist))
print(ans)

Submission status: Wrong Answer

Solution code:
def stdin():
    return map(int, input().split())


N, Q = stdin()

parent_vertex = [0] * N

for _ in range(N - 1):
    a, b = stdin()
    parent_vertex[b - 1] = a - 1

operations = [0] * N

for _ in range(Q):
    p, x = stdin()
    operations[p - 1] += x

counter = [0] * N

for i in range(N):
    counter[i] += operations[i]
    if not i:
        continue
    parent = parent_vertex[i]
    counter[i] += counter[parent]

print(*counter)

Submission status: Wrong Answer

Solution code:
n,q = map(int, input().split())
counter = [0] * n
edge = [[] for _ in range(n)]
for _ in range(n - 1):
    a,b = map(int, input().split())
    edge[a - 1].append(b - 1)
    edge[b - 1].append(a - 1)
    
for _ in range(q):
    p,x = map(int, input().split())
    counter[p - 1] += x
for i,c in enumerate(counter):
    if c == 0:
        continue
    for e in edge[i]:
        counter[e] +=c
print(*counter)

Submission status: Wrong Answer

Solution code:
from collections import deque, defaultdict

import sys
inputs = sys.stdin.readlines()
n, q = list(map(int, inputs[0].split()))

def dfs_generator(nodes, start):
    nexts = deque([start])
    while nexts:
        node = nexts.popleft()
        nexts.extend(nodes[node]['childs'])
        yield node

nodes = defaultdict(lambda: dict({'val': 0, 'childs': []}))
for x in inputs[1:n]:
    from_, to_ = map(int, x.split())
    nodes[from_]['childs'].append(to_)

subtree_roots = defaultdict(int)
for x in inputs[n:]:
    node, val = map(int, x.split())
    subtree_roots[node] += val

subtrees = defaultdict(list)
for root, val in subtree_roots.items():
    gen = dfs_generator(nodes, root)
    try:
        while True:
            node = next(gen)
            subtrees[root].append(node) 
    except StopIteration:
        pass
    for node in subtrees[root]:
        nodes[node]['val'] += val

for i in range(1, n):
    print('%d' %(nodes[i]['val']), end=' ')
print('%d' %(nodes[i+1]['val']))

Submission status: Wrong Answer

Solution code:
# Ki
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)]

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

# まずpで指定された木だけにxを足す		
for i in range(Q):
	p = px[i][0]
	x = px[i][1]
	anslist[p-1] += x 
	
# 次にpで指定された木の根全てにxを足す(その木は除く)
ab = sorted(ab) # aが小さい順にソート
for i in range(N-1):
	a = ab[i][0]
	b = ab[i][1]
	anslist[b-1] += anslist[a-1]

print(anslist)

Submission status: Wrong Answer

Solution code:
n,q = map(int, input().split())
counter = [0] * n
edge = [[] for _ in range(n)]
for _ in range(n - 1):
    a,b = map(int, input().split())
    edge[a - 1].append(b - 1)
for _ in range(q):
    p,x = map(int, input().split())
    counter[p - 1] += x
for i,c in enumerate(counter):
    if c == 0:
        continue
    for e in edge[i]:
        counter[e] +=c
print(*counter)

Submission status: Wrong Answer

Solution code:
def stdin():
    return map(int, input().split())


N, Q = stdin()

parent_vertex = [0] * N

for _ in range(N - 1):
    a, b = stdin()
    parent_vertex[b - 1] = a - 1

operations = [0] * N

for _ in range(Q):
    p, x = stdin()
    operations[p - 1] += x

counter = [0] * N

for i in range(N):
    counter[i] += operations[i]
    if i > 0:
        counter[i] += counter[parent_vertex[i]]

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

Submission status: Wrong Answer

Solution code:
nq = [int(x) for x in input().split(' ')]

ablist = []
for n in range(nq[0] - 1):
    ab = [int(x) for x in input().split(' ')]
    ablist.append(ab)

pqlist = []
for q in range(nq[1]):
    pq = [int(x) for x in input().split(' ')]
    pqlist.append(pq)
  
rlist = []
for n in range(nq[0]):
    rlist.append(0)
    
for pq in pqlist:
    if pq[0] == 1:
        for i in range(len(rlist)):
            rlist[i] += pq[1]
            
        continue
    
    rlist[pq[0] - 1] += pq[1]
    
    for ab in ablist:
        if ab[0] == pq[0]:
            rlist[ab[1] - 1] += pq[1]

print(*rlist)

Submission status: Wrong Answer

Solution code:
#D
num=input().split()
N=int(num[0])
Q=int(num[1])
a=[]
b=[]
for i in range(N-1):
    num=input().split()
    a.append(int(num[0]))
    b.append(int(num[1]))
p=[]
x=[]
for _ in range(Q):
    num=input().split()
    p.append(int(num[0]))
    x.append(int(num[1]))
c=[0]*N
for i in range(Q):
    c[p[i]-1]=c[p[i]-1]+x[i]
for i in range(1,N-1):
    k=i
    for j in range(i):
        if a[i-j-1]>a[k]:
            a[k],a[i-j-1]=a[i-j-1],a[k]
            b[k],b[i-j-1]=b[i-j-1],b[k]
            k=k-1
        else:
            break
for i in range(N-1):
    c[b[i]-1]=c[b[i]-1]+c[a[i]-1]
s=str(c[0])
for i in range(1,N):
    s=s+" "+str(c[i])
print(s)

Submission status: Wrong Answer

Solution code:
nq = [int(x) for x in input().split(' ')]

ablist = []
for n in range(nq[0] - 1):
    ab = [int(x) for x in input().split(' ')]
    ablist.append(ab)

pqlist = []
for q in range(nq[1]):
    pq = [int(x) for x in input().split(' ')]
    pqlist.append(pq)
    
rlist = []
for n in range(nq[0]):
    rlist.append(0)
    
for pq in pqlist:
    if pq[0] == 1:
        for i in range(len(rlist)):
            rlist[i] += pq[1]
            
        continue
    
    rlist[pq[0] - 1] += pq[1]
    
    for ab in ablist:
        if ab[0] == pq[0]:
            rlist[ab[1] - 1] += pq[1]

print(rlist)

Submission status: Wrong Answer

Solution code:
import sys
inputs = sys.stdin.readlines()

n, q = list(map(int, inputs[0].split()))
edges = []
for i in range(n-1):
    edges.append(tuple(map(int, inputs[i+1].split())))
p_x_list = []
for i in range(q):
    p_x_list.append(tuple(map(int, inputs[n+i].split())))
    
from collections import deque

def dfs_generator(nodes, start):
    nexts = deque([start])
    while nexts:
        node = nexts.popleft()
        nexts.extend(nodes[node]['childs'])
        yield node
'''
nodes = dict({1: dict({'val': 0, 'parent': 0, 'childs': []})})
for from_, to_ in edges:
    nodes[from_]['childs'].append(to_)
    nodes[to_] = dict({'val': 0, 'parent': from_, 'childs': []})

for p, x in p_x_list:
    gen = dfs_generator(nodes, p)
    try:
        while True:
            nodes[next(gen)]['val'] += x
    except StopIteration:
        pass

for i in range(n-1):
    print(str(nodes[i+1]['val']), end=' ')
print(str(nodes[i+2]['val']))
'''

Submission status: Wrong Answer

Solution code:
def stdin():
    return map(int, input().split())


N, Q = stdin()

parent_vertex = [0] * N

for _ in range(N - 1):
    a, b = stdin()
    parent_vertex[b - 1] = a - 1

operations = {i: 0 for i in range(N)}

for _ in range(Q):
    p, x = stdin()
    operations[p - 1] += x

counter = [0] * N

for i in range(N):
    counter[i] += operations[i]
    if i > 0:
        counter[i] += counter[parent_vertex[i]]

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

Submission status: Wrong Answer

Solution code:
N, Q = [int(i) for i in input().split(' ')]
tree = {}
for i in range(1, N+1):
  tree[i] = {'children': [], 'num': 0}
  
for _ in range(N-1):
  a, b = [int(i) for i in input().split(' ')]
  tree[a]['children'].append(b)

for t in reversed(list(tree.values())):
  for c in t['children']:
  	t['children'] += tree[c]['children']
    
for _ in range(Q):
  a, num = [int(i) for i in input().split(' ')]
  tree[a]['num'] += num
  for c in tree[a]['children']:
    tree[c]['num'] += num

print(*[t['num'] for t in tree.values()])

Submission status: Wrong Answer

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

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

tree = [[] for _ in range(n)]

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

counter = [0] * n

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

query = deque([(0, -1)]) # current, parent
while query:
    current, parent = query.popleft()
    value = counter[current]
    for node in tree[current]:
        if node == parent:
            continue
        else:
            counter[node] += value
            query.append((node, current))
            print(query)

print(*counter)

Submission status: Wrong Answer

Solution code:
n, q = list(map(int, input().split()))
edge = [list(map(int, input().split())) for _ in range(n-1)]
ope = [list(map(int, input().split())) for _ in range(q)]
edge = sorted(edge, key=lambda x:x[0])
vertex = [0]*n
for i, v in ope:
    vertex[i-1] += v
for p, c in edge:
    vertex[c-1] += vertex[p-1]
print(*vertex)

Submission status: Wrong Answer

Solution code:
N, Q = map(int, input().split())
a = [[x] for x in range(N)]
for _ in range(N-1):
    a1, b1 = map(int, input().split())
    for i in a:
        if a1 - 1 in i:
            i.append(b1-1)
cnt = [0] * N
for i in range(Q):
    p, x = map(int, input().split())
    tmp = a[p-1]
    for j in tmp:
        cnt[j] += x

print(*cnt)

Submission status: Wrong Answer

Solution code:
import sys
inputs = sys.stdin.readlines()
 
n, q = list(map(int, inputs[0].split()))
edges = []
for i in range(n-1):
    edges.append(tuple(map(int, inputs[i+1].split())))
p_x_list = []
for i in range(q):
    p_x_list.append(tuple(map(int, inputs[n+i].split())))

Submission status: Wrong Answer

Solution code:
import sys
from collections import Counter
from collections import defaultdict
sys.setrecursionlimit(10**8)
input = lambda: sys.stdin.readline()[:-1]
cnt=Counter()
data=defaultdict(set)
visited=Counter()
n,q=map(int,input().split())
ab=[tuple(map(int,input().split())) for i in range(n-1)]
px=[tuple(map(int,input().split())) for i in range(q)]
ab.sort(key=lambda tup:(tup[0],tup[1]))
for i in ab:
	data[i[0]].add(i[1])
	data[i[1]].add(i[0])
for j in px:
	cnt[j[0]]+=j[1]

def plus(now,value):
	for i in data[now]:
		if not visited[i]:
			cnt[i]+=value
			visited[i]=1
			print(cnt)	
			plus(i,cnt[i])
		
		
cnt[1]+=0
visited[1]=1
plus(1,cnt[1])
print(cnt)

ans=list(cnt.items())
ans.sort(key=lambda tup:tup[0])
ans =[str(i[1]) for i in ans]
print(' '.join(ans))

Submission status: Wrong Answer

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

def solve():
  n,q = (int(i) for i in input().split())
  graph = [[] for _ in range(n)]
  
  for i in range(n-1):
    a,b = (int(i) for i in input().split())
    graph[a-1].append(b-1)
  ans = [0]*n
  
  for i in range(q):
    p,x = (int(i) for i in input().split())
    ans[p-1] += x

  query = deque([0])
  while query:
    nowplace = query.popleft()
    nowvalue = ans[nowplace]
    for node in graph[nowplace]:
      ans[node] += nowvalue
      query.append(node)
      
  print(*ans)
  
solve()

Submission status: Wrong Answer

Solution code:
import sys


def main():
    input = sys.stdin.readline
    n, q = map(int, input().split())
    #n, q = map(int, "4 3".split())
    g = [[] for _ in range(n)]
    for i in range(n-1):
        a, b = map(int, input().split())
        #a, b = map(int, ["1 2", "2 3", "2 4"][i].split())
        g[a-1].append(b-1)

    ans = [0] * n
    def dfs(start, point):
        stack = [start]
        while stack:
            x = stack.pop()
            ans[x] += point
            stack += g[x]

    for i in range(q):
        p, v = map(int, input().split())
        #p, v = map(int, ["2 10", "1 100", "3 1"][i].split())
        dfs(p-1, v)

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

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

"""
if __name__ == '__main__':
    main()
"""

n, q = map(int, input().split())
#n, q = map(int, "4 3".split())
g = [[] for _ in range(n)]
for i in range(n-1):
    a, b = map(int, input().split())
    #a, b = map(int, ["1 2", "2 3", "2 4"][i].split())
    g[a-1].append(b-1)

ans = [0] * n
def dfs(start, point):
    stack = [start]
    while stack:
        x = stack.pop()
        ans[x] += point
        stack += g[x]

for i in range(q):
    p, v = map(int, input().split())
    #p, v = map(int, ["2 10", "1 100", "3 1"][i].split())
    dfs(p-1, v)

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

Submission status: Wrong Answer

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


if __name__ == '__main__':
    main()
"""
n, q = map(int, input().split())
#n, q = map(int, "4 3".split())

g = []
for i in range(n):
    g.append([])
for i in range(n-1):
    a, b = map(int, input().split())
    #a, b = map(int, ["1 2", "2 3", "2 4"][i].split())
    g[a-1].append(b-1)

ans = [0] * n
def dfs(start, point):
    stack = [start]
    while stack:
        x = stack.pop()
        ans[x] += point
        stack += g[x]

for i in range(q):
    p, v = map(int, input().split())
    #p, v = map(int, ["2 10", "1 100", "3 1"][i].split())
    dfs(p-1, v)

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

Submission status: Wrong Answer

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


if __name__ == '__main__':
    main()
"""
n, q = map(int, input().split())
#n, q = map(int, "4 3".split())
print(n, q)

g = []
for i in range(n):
    g.append([])
for i in range(n-1):
    a, b = map(int, input().split())
    #a, b = map(int, ["1 2", "2 3", "2 4"][i].split())
    g[a-1].append(b-1)

ans = [0] * n
def dfs(start, point):
    stack = [start]
    while stack:
        x = stack.pop()
        ans[x] += point
        stack += g[x]

for i in range(q):
    p, v = map(int, input().split())
    #p, v = map(int, ["2 10", "1 100", "3 1"][i].split())
    print(p,v)
    dfs(p-1, v)

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

Submission status: Wrong Answer

Solution code:
# https://atcoder.jp/contests/abc138/tasks/abc138_d

from collections import deque

def bfs(graph, start, query, n):
    queue = deque([])
    acc = query[start] if start in query else 0
    queue.append([start, acc])
    ans = [0] * (n)
    ans[start] = acc

    while queue:
        idx, acc = queue.popleft()
        for child in graph[idx].keys():
            if ans[child]:
                continue
            ans[child] = acc
            if child in query:
                ans[child] += query[child]
            queue.append([child, ans[child]])
    
    print(' '.join(map(str, ans)))

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

query = {}
for _ in range(q):
    p, x = map(int,input().split())
    p -= 1
    if p not in query:
        query[p] = x
    else:
        query[p] += x
bfs(tree, start, query, n)

Submission status: Wrong Answer

Solution code:
# https://atcoder.jp/contests/abc138/tasks/abc138_d

from collections import deque

def bfs(graph, start, query):
    queue = deque([])
    acc = query[start] if start in query else 0
    queue.append([start, acc])
    ans = {start:acc}

    while queue:
        idx, acc = queue.popleft()
        for child in graph[idx].keys():
            if child in ans:
                continue
            ans[child] = acc
            if child in query:
                ans[child] += query[child]
            print(child)
            queue.append([child, ans[child]])
    [print(ans[i], end=' ') for i in range(1, n+1)]

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

query = {}
for _ in range(q):
    p, x = map(int,input().split())
    if p not in query:
        query[p] = x
    else:
        query[p] += x
bfs(tree, start, query)

Submission status: Wrong Answer

Solution code:
### D
N, Q = map(int, input().split())
tree = [[] for i in range(N)]
counter =[0 for i in range(N)]
for i in range(N-1):
    a, b= map(int,input().split())
    tree[a-1].append(b-1)
for i in range(1,Q+1):
    p,x = map(int,input().split())
    counter[p-1] += x
    connectlist = [p-1]
    for j in tree[p-1]:
        counter[j] += x
        connectlist.append(j)
        for k in range(j,N):
            if not(k in connectlist) and k in tree[j]:
                counter[k] += x
                connectlist.append(k)
       
print(' '.join(list(map(str,counter))))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
n, q = map(int, input().split())
 
stack = [[] for _ in range(n+1)]
for i in range(n-1):
  a,b = map(int, input().split())
  stack[a-1].append(b)

ans = [0] * n
for i in range(q):
  p, x = map(int, input().split())
  ans[p-1] += x
def dfs(cur):
    if len(stack[cur-1]) <= 0:
      return
    for c in stack[cur-1]:
      ans[c-1] += ans[cur-1] 
      dfs(c)
dfs(1)
print(*ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
n, q = map(int, input().split())
 
stack = [[] for _ in range(n+1)]
stack[0].append(1)
for i in range(n-1):
  a,b = map(int, input().split())
  stack[a].append(b)

ans = [0] * n
pool = {}
def dfs(cur, num):
	ans[cur-1] += num
	if len(stack[cur]) <= 0:
		return
	for c in stack[cur]:
		dfs(c, num)

for i in range(q):
  p, x = map(int, input().split())
  pool[p] = pool.get(p, 0) + x
for k, v in pool.items():
  dfs(k, v)
print(*ans)

Submission status: Wrong Answer

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

ans = [0]*(n+1)
ki = {}
for i in range(1,n+1):
    ki[i] = []

#z = ["1 2", "2 3", "2 4"]

for i in range(n-1):
    e = list(map(int, input().split()))
    #e = list(map(int, z[i].split()))
    ki[e[0]].append(e[1])

#print(ki)

def df(graph, start, point):
    stack = [start]
    visited = []
    while stack:
        v = stack.pop(0)
        ans[v - 1] += point
        if v not in visited:
            visited.append(v)
            stack = graph.get(v, []) + stack

#y = ["2 10", "1 100", "3 1"]
for i in range(q):
    p = list(map(int, input().split()))
    #p = list(map(int, y[i].split()))
    df(ki, p[0], p[1])

#print(' '.join(list(map(str, ans))))
for n in ans:
    print(n, end=" ")

Submission status: Wrong Answer

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

ans = [0]*n
ki = {}
for i in range(1,n+1):
    ki[i] = []

#z = ["1 2", "2 3", "2 4"]

for i in range(n-1):
    e = list(map(int, input().split()))
    #e = list(map(int, z[i].split()))
    ki[e[0]].append(e[1])

#print(ki)

def df(graph, start, point):
    stack = [start]
    visited = []
    while stack:
        v = stack.pop(0)
        ans[v - 1] += point
        if v not in visited:
            visited.append(v)
            stack = graph.get(v, []) + stack

#y = ["2 10", "1 100", "3 1"]
for i in range(q):
    p = list(map(int, input().split()))
    #p = list(map(int, y[i].split()))
    df(ki, p[0], p[1])

#print(' '.join(list(map(str, ans))))
for n in ans:
    print(n, end=" ")

Submission status: Wrong Answer

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

ans = [0]*n
ki = {}
for i in range(1,n+1):
    ki[i] = []

#z = ["1 2", "2 3", "2 4"]

for i in range(n-1):
    e = list(map(int, input().split()))
    #e = list(map(int, z[i].split()))
    ki[e[0]].append(e[1])

#print(ki)

def df(graph, start, point):
    stack = [start]
    visited = []
    while stack:
        v = stack.pop(0)
        ans[v - 1] += point
        if v not in visited:
            visited.append(v)
            stack = graph.get(v, []) + stack

#y = ["2 10", "1 100", "3 1"]
for i in range(q):
    p = list(map(int, input().split()))
    #p = list(map(int, y[i].split()))
    df(ki, p[0], p[1])

print(' '.join(list(map(str, ans))))
#for n in ans:
#    print(n, end=" ")