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: Time Limit Exceeded

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)

ans = []
lines_dict =None
d=None
def main():
    global AB, PX
    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(1, N+1):
            AB[i] = []
            PX[i] = 0
        for i in range(N-1):
            #  AB.append(LI())
            a, b = LI()
            AB[a] += [b]
            AB[b] += [a]

        for i in range(Q):
            p, x = LI()
            PX[p] += x
        perr(AB)
        perr(PX)
        dfs(1, -1)
        for i in sorted(PX.keys()):
            print(PX[i], end=' ')
        #  ans = [0 for _ in range(N)]

def dfs(parent, parent_parent):
    perr(PX)
    for node in AB[parent]:
        if node != parent_parent:
            perr(node)
            if node not in PX.keys():
                PX[node] = 0
            PX[node] += PX[parent]
            dfs(node, parent)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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)

ans = []
lines_dict =None
d=None
def main():
    global AB, PX
    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(1, N+1):
            AB[i] = set()
            PX[i] = 0
        for i in range(N-1):
            #  AB.append(LI())
            a, b = LI()
            AB[a].add(b)
            AB[b].add(a)

        for i in range(Q):
            p, x = LI()
            PX[p] += x
        perr(AB)
        perr(PX)
        dfs(1, -1)
        for i in sorted(PX.keys()):
            print(PX[i], end=' ')
        #  ans = [0 for _ in range(N)]

def dfs(parent, parent_parent):
    perr(PX)
    for node in AB[parent]:
        if node != parent_parent:
            perr(node)
            if node not in PX.keys():
                PX[node] = 0
            PX[node] += PX[parent]
            dfs(node, parent)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

from collections import deque

def dfs(graph, start, ans, n):
    queue = deque([])
    queue.append(start)
    visited = [False] * n
    visited[start] = True

    while queue:
        parent = queue.pop()
        for child in graph[parent].keys():
            if visited[child]:
                continue
            ans[child] += ans[parent]
            queue.append(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

ans = [0]*n
for _ in range(q):
    p, x = map(int,input().split())
    p -= 1
    ans[p] += x
dfs(tree, start, ans, n)

Submission status: Time Limit Exceeded

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

from collections import deque

def dfs(graph, start, ans, n):
    queue = deque([])
    queue.append(start)
    visited = [False] * n
    visited[start] = True

    while queue:
        parent = queue.popleft()
        for child in graph[parent].keys():
            if visited[child]:
                continue
            visited[child] = True
            ans[child] += ans[parent]
            queue.append(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

ans = [0]*n
for _ in range(q):
    p, x = map(int,input().split())
    p -= 1
    ans[p] += x
dfs(tree, start, ans, n)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(2*10**5)
def parent(array,count,index,root):
    count[index-1]+=count[root-1]
    for i in array[index-1]:
        if i!=root:
            parent(array,count,i,index)
num,q=map(int,input().split())
counter=[0 for _ in range(num)]
roots=[[] for _ in range(num)]
for _ in range(num-1):
    a,b=map(int,input().split())
    roots[a-1].append(b)
    roots[b-1].append(a)
for _ in range(q):
    p,x=map(int,input().split())
    counter[p-1]+=x
for ele in roots[0]:
    parent(roots,counter,ele,1)
print(" ".join([str(n) for n in counter]))

Submission status: Time Limit Exceeded

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

n,q = map(int,input().split())
score = [0]*(n+1)
tree = [() for i in range(n+1)]
check = [1]+[1]+[0]*(n-1)

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

que = deque([1])
qappend = que.append
qpop = que.pop

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

while que:
  n = qpop()
  for i in tree[n]:
    if check[i]:continue
    check[i] = 1
    score[i] += score[n]
    qappend(i)

print(*score[1:])

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(2*10**5)
def parent(array,count,index,root):
    count[index-1]+=count[root-1]
    for i in array[index-1]:
        if i!=root:
            parent(array,count,i,index)
num,q=map(int,input().split())
counter=[0 for _ in range(num)]
roots=[set() for _ in range(num)]
for _ in range(num-1):
    a,b=map(int,input().split())
    roots[a-1].add(b)
    roots[b-1].add(a)
for _ in range(q):
    p,x=map(int,input().split())
    counter[p-1]+=x
for ele in roots[0]:
    parent(roots,counter,ele,1)
print(" ".join([str(n) for n in counter]))

Submission status: Time Limit Exceeded

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)

ans = []
lines_dict =None
d=None
def main():
    global d
    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(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 i in range(N+1):
        d[i] = 0
    for p, x in PX:
        if p not in d.keys():
            d[p] = 0
        d[p] += x
    perr(d)
    """
    根からスタートするとは？
    1-5-3とかっていう組み合わせがあるため、dfsで根から辿っていく必要がある

    """
    global ans
    ans = [0 for _ in range(N)]
    ans[0] = d[1]

    global lines_dict
    lines_dict = {}
    for ab in AB:
        if ab[0] not in lines_dict.keys():
            lines_dict[ab[0]] = {ab[1]}
        else:
            lines_dict[ab[0]].add(ab[1])

        if ab[1] not in lines_dict.keys():
            lines_dict[ab[1]] = {ab[0]}
        else:
            lines_dict[ab[1]].add(ab[0])

    if 'LOCAL' in os.environ:
        pdb.set_trace()
    perr(lines_dict)
    #  exit()




        #  new_AB = []
        #  target_lines = []
        #  for ab in AB:
        #      if current_node in ab and ab[0] not in done_list and ab[1] not in done_list:
        #          target_lines.append(ab)
        #      else:
        #          new_AB.append(ab)
        #  target_lines = [ab for ab in AB if current_node in ab and ab[0] not in done_list and ab[1] not in done_list]
        #  if current_node not in lines_dict.keys():
        #      return
        #  target_lines = [num for num in lines_dict[current_node] if num not in done_list]
        #  done_list.append(current_node)
        #  for to_node in target_lines:
        #      perr(to_node)
        #      ans[to_node-1] = val + d[to_node]
        #      dfs(to_node, ans[to_node-1], done_list)

    dfs(1, d[1], None)
    perr(ans)
    print(' '.join(map(lambda x: str(x), ans)))


def dfs(current_node, val, parent_node):
    for other_node in lines_dict[current_node]:
        if other_node == parent_node:
            continue
        # まだ訪れていないので訪問
        new_val = val + d[other_node]
        ans[other_node-1] = new_val
        dfs(other_node, new_val, current_node)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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)

def main():
    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(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 i in range(N+1):
        d[i] = 0
    for p, x in PX:
        if p not in d.keys():
            d[p] = 0
        d[p] += x
    perr(d)
    """
    根からスタートするとは？
    1-5-3とかっていう組み合わせがあるため、dfsで根から辿っていく必要がある

    """
    ans = [0 for _ in range(N)]
    ans[0] = d[1]

    lines_dict = {}
    for ab in AB:
        if ab[0] not in lines_dict.keys():
            lines_dict[ab[0]] = {ab[1]}
        else:
            lines_dict[ab[0]].add(ab[1])

        if ab[1] not in lines_dict.keys():
            lines_dict[ab[1]] = {ab[0]}
        else:
            lines_dict[ab[1]].add(ab[0])

    if 'LOCAL' in os.environ:
        pdb.set_trace()
    perr(lines_dict)
    #  exit()


    def dfs(current_node, val, parent_node):
        for other_node in lines_dict[current_node]:
            if other_node == parent_node:
                continue
            # まだ訪れていないので訪問
            new_val = val + d[other_node]
            ans[other_node-1] = new_val
            dfs(other_node, new_val, current_node)


        #  new_AB = []
        #  target_lines = []
        #  for ab in AB:
        #      if current_node in ab and ab[0] not in done_list and ab[1] not in done_list:
        #          target_lines.append(ab)
        #      else:
        #          new_AB.append(ab)
        #  target_lines = [ab for ab in AB if current_node in ab and ab[0] not in done_list and ab[1] not in done_list]
        #  if current_node not in lines_dict.keys():
        #      return
        #  target_lines = [num for num in lines_dict[current_node] if num not in done_list]
        #  done_list.append(current_node)
        #  for to_node in target_lines:
        #      perr(to_node)
        #      ans[to_node-1] = val + d[to_node]
        #      dfs(to_node, ans[to_node-1], done_list)

    dfs(1, d[1], None)
    perr(ans)
    print(' '.join(map(lambda x: str(x), ans)))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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(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 i in range(N+1):
    d[i] = 0
for p, x in PX:
    if p not in d.keys():
        d[p] = 0
    d[p] += x
perr(d)
"""
根からスタートするとは？
1-5-3とかっていう組み合わせがあるため、dfsで根から辿っていく必要がある

"""
ans = [0 for _ in range(N)]
ans[0] = d[1]

lines_dict = {}
for ab in AB:
    if ab[0] not in lines_dict.keys():
        lines_dict[ab[0]] = [ab[1]]
    else:
        lines_dict[ab[0]].append(ab[1])

    if ab[1] not in lines_dict.keys():
        lines_dict[ab[1]] = [ab[0]]
    else:
        lines_dict[ab[1]].append(ab[0])

if 'LOCAL' in os.environ:
    pdb.set_trace()
perr(lines_dict)
#  exit()


def dfs(current_node, val, parent_node):
    for other_node in set(lines_dict[current_node]):
        if other_node == parent_node:
            continue
        # まだ訪れていないので訪問
        new_val = val + d[other_node]
        ans[other_node-1] = new_val
        dfs(other_node, new_val, current_node)


    #  new_AB = []
    #  target_lines = []
    #  for ab in AB:
    #      if current_node in ab and ab[0] not in done_list and ab[1] not in done_list:
    #          target_lines.append(ab)
    #      else:
    #          new_AB.append(ab)
    #  target_lines = [ab for ab in AB if current_node in ab and ab[0] not in done_list and ab[1] not in done_list]
    #  if current_node not in lines_dict.keys():
    #      return
    #  target_lines = [num for num in lines_dict[current_node] if num not in done_list]
    #  done_list.append(current_node)
    #  for to_node in target_lines:
    #      perr(to_node)
    #      ans[to_node-1] = val + d[to_node]
    #      dfs(to_node, ans[to_node-1], done_list)


if __name__ == '__main__':
    dfs(1, d[1], None)
    perr(ans)
    print(' '.join(map(lambda x: str(x), ans)))

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
sys.setrecursionlimit(2*10**5)
n,q=map(int,input().split())
graph=[[] for _ in range(n)]
for _ in range(n-1):
    a,b=map(int,input().split())
    graph[a-1].append(b-1)
    graph[b-1].append(a-1)
prev=[-1]*n
prev[0]=0
def f(n):
    for i in graph[n]:
        if prev[i]==-1:
            prev[i]=n
            f(i)
f(0)
counter=[0]*n
for _ in range(q):
    p,x=map(int,input().split())
    counter[p-1]+=x
score=[0]*n
score[0]=counter[0]
stack=[0]
while stack!=[]:
    memo=[]
    for i in stack:
        for j in graph[i]:
            if j!=prev[i]:
                score[j]=score[i]+counter[j]
                memo.append(j)
    stack=memo
for k in score:
    print(k,end=" ")

Submission status: Time Limit Exceeded

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(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 i in range(N+1):
    d[i] = 0
for p, x in PX:
    if p not in d.keys():
        d[p] = 0
    d[p] += x
perr(d)
"""
根からスタートするとは？
1-5-3とかっていう組み合わせがあるため、dfsで根から辿っていく必要がある

"""
ans = [0 for _ in range(N)]
ans[0] = d[1]

lines_dict = {}
for ab in AB:
    if ab[0] not in lines_dict.keys():
        lines_dict[ab[0]] = [ab[1]]
    else:
        lines_dict[ab[0]].append(ab[1])

    if ab[1] not in lines_dict.keys():
        lines_dict[ab[1]] = [ab[0]]
    else:
        lines_dict[ab[1]].append(ab[0])

if 'LOCAL' in os.environ:
    pdb.set_trace()
perr(lines_dict)
#  exit()


def dfs(current_node, val, parent_node):
    for other_node in lines_dict[current_node]:
        if other_node == parent_node:
            continue
        # まだ訪れていないので訪問
        new_val = val + d[other_node]
        ans[other_node-1] = new_val
        dfs(other_node, new_val, current_node)


    #  new_AB = []
    #  target_lines = []
    #  for ab in AB:
    #      if current_node in ab and ab[0] not in done_list and ab[1] not in done_list:
    #          target_lines.append(ab)
    #      else:
    #          new_AB.append(ab)
    #  target_lines = [ab for ab in AB if current_node in ab and ab[0] not in done_list and ab[1] not in done_list]
    #  if current_node not in lines_dict.keys():
    #      return
    #  target_lines = [num for num in lines_dict[current_node] if num not in done_list]
    #  done_list.append(current_node)
    #  for to_node in target_lines:
    #      perr(to_node)
    #      ans[to_node-1] = val + d[to_node]
    #      dfs(to_node, ans[to_node-1], done_list)


if __name__ == '__main__':
    dfs(1, d[1], None)
    perr(ans)
    print(' '.join(map(lambda x: str(x), ans)))

Submission status: Time Limit Exceeded

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(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 i in range(N+1):
    d[i] = 0
for p, x in PX:
    if p not in d.keys():
        d[p] = 0
    d[p] += x
perr(d)
"""
根からスタートするとは？
1-5-3とかっていう組み合わせがあるため、dfsで根から辿っていく必要がある

"""
ans = [0 for _ in range(N)]
ans[0] = d[1]

lines_dict = {}
for ab in AB:
    if ab[0] not in lines_dict.keys():
        lines_dict[ab[0]] = [ab[1]]
    else:
        lines_dict[ab[0]].append(ab[1])

    if ab[1] not in lines_dict.keys():
        lines_dict[ab[1]] = [ab[0]]
    else:
        lines_dict[ab[1]].append(ab[0])

if 'LOCAL' in os.environ:
    pdb.set_trace()
perr(lines_dict)
#  exit()


def dfs(current_node, val, parent_node):
    for other_node in lines_dict[current_node]:
        if other_node == parent_node:
            continue
        # まだ訪れていないので訪問
        new_val = val + d[other_node]
        ans[other_node-1] = new_val
        dfs(other_node, new_val, current_node)


    #  new_AB = []
    #  target_lines = []
    #  for ab in AB:
    #      if current_node in ab and ab[0] not in done_list and ab[1] not in done_list:
    #          target_lines.append(ab)
    #      else:
    #          new_AB.append(ab)
    #  target_lines = [ab for ab in AB if current_node in ab and ab[0] not in done_list and ab[1] not in done_list]
    #  if current_node not in lines_dict.keys():
    #      return
    #  target_lines = [num for num in lines_dict[current_node] if num not in done_list]
    #  done_list.append(current_node)
    #  for to_node in target_lines:
    #      perr(to_node)
    #      ans[to_node-1] = val + d[to_node]
    #      dfs(to_node, ans[to_node-1], done_list)


dfs(1, d[1], None)
perr(ans)
print(' '.join(map(lambda x: str(x), ans)))

Submission status: Time Limit Exceeded

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(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 i in range(N+1):
    d[i] = 0
for p, x in PX:
    if p not in d.keys():
        d[p] = 0
    d[p] += x
perr(d)
"""
根からスタートするとは？
1-5-3とかっていう組み合わせがあるため、dfsで根から辿っていく必要がある

"""
ans = [0 for _ in range(N)]
ans[0] = d[1]

lines_dict = {}
for ab in AB:
    is_continued = False
    if ab[0] not in lines_dict.keys():
        lines_dict[ab[0]] = [ab[1]]
    else:
        lines_dict[ab[0]].append(ab[1])

    if ab[1] not in lines_dict.keys():
        lines_dict[ab[1]] = [ab[0]]
    else:
        lines_dict[ab[1]].append(ab[0])

perr(lines_dict)
#  exit()


def dfs(current_node, val, parent_node):
    if parent_node:
        lines_dict[current_node].remove(parent_node)

    for other_node in lines_dict[current_node]:
        # まだ訪れていないので訪問
        new_val = val + d[other_node]
        ans[other_node-1] = new_val
        dfs(other_node, new_val, current_node)


    #  new_AB = []
    #  target_lines = []
    #  for ab in AB:
    #      if current_node in ab and ab[0] not in done_list and ab[1] not in done_list:
    #          target_lines.append(ab)
    #      else:
    #          new_AB.append(ab)
    #  target_lines = [ab for ab in AB if current_node in ab and ab[0] not in done_list and ab[1] not in done_list]
    #  if current_node not in lines_dict.keys():
    #      return
    #  target_lines = [num for num in lines_dict[current_node] if num not in done_list]
    #  done_list.append(current_node)
    #  for to_node in target_lines:
    #      perr(to_node)
    #      ans[to_node-1] = val + d[to_node]
    #      dfs(to_node, ans[to_node-1], done_list)


dfs(1, d[1], None)
perr(ans)
print(' '.join(map(lambda x: str(x), ans)))

Submission status: Time Limit Exceeded

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 i in range(N+1):
    d[i] = 0
for p, x in PX:
    if p not in d.keys():
        d[p] = 0
    d[p] += x
perr(d)
"""
根からスタートするとは？
1-5-3とかっていう組み合わせがあるため、dfsで根から辿っていく必要がある

"""
ans = [0 for _ in range(N)]
ans[0] = d[1]

lines_dict = {}
for ab in AB:
    is_continued = False
    if ab[0] not in lines_dict.keys():
        lines_dict[ab[0]] = [ab[1]]
    else:
        lines_dict[ab[0]].append(ab[1])

    if ab[1] not in lines_dict.keys():
        lines_dict[ab[1]] = [ab[0]]
    else:
        lines_dict[ab[1]].append(ab[0])

perr(lines_dict)
#  exit()

def dfs(current_node, val, done_list):
    for other_node in lines_dict[current_node]:
        if other_node not in done_list:
            # まだ訪れていないので訪問
            new_val = val + d[other_node]
            ans[other_node-1] = new_val
            dfs(other_node, new_val, done_list + [other_node])


    #  new_AB = []
    #  target_lines = []
    #  for ab in AB:
    #      if current_node in ab and ab[0] not in done_list and ab[1] not in done_list:
    #          target_lines.append(ab)
    #      else:
    #          new_AB.append(ab)
    #  target_lines = [ab for ab in AB if current_node in ab and ab[0] not in done_list and ab[1] not in done_list]
    #  if current_node not in lines_dict.keys():
    #      return
    #  target_lines = [num for num in lines_dict[current_node] if num not in done_list]
    #  done_list.append(current_node)
    #  for to_node in target_lines:
    #      perr(to_node)
    #      ans[to_node-1] = val + d[to_node]
    #      dfs(to_node, ans[to_node-1], done_list)


dfs(1, d[1], [1])
perr(ans)
print(' '.join(map(lambda x: str(x), ans)))