Approach
Breadth-first search
For ABC187 E — Through Path, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 89 lines of Python from the credited upstream file abc187_e.py.
- The implementation visibly relies on sequence storage, ordered lookup, work queue.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12 3 4def calc_depth(vertex_count: int, graph):5 from collections import deque6 7 PENDING = -18 depth = [PENDING for _ in range(vertex_count)]9 parent = [PENDING for _ in range(vertex_count)]10 depth[0], parent[0] = 0, 011 d = deque()12 d.append(0)13 14 while d:15 vertex = d.popleft()16 17 for g in graph[vertex]:18 if depth[g] == PENDING:19 depth[g] = depth[vertex] + 120 parent[g] = vertex21 d.append(g)22 23 return depth24 25 26def run_imos(graph, depth, imos):27 from collections import deque28 29 d = deque()30 d.append(0)31 32 while d:33 vertex = d.popleft()34 35 for g in graph[vertex]:36 if depth[vertex] < depth[g]:37 imos[g] += imos[vertex]38 d.append(g)39 40 return imos41 42 43def main():44 import sys45 46 input = sys.stdin.readline47 48 n = int(input())49 graph = [[] for _ in range(n)]50 a = [0 for _ in range(n - 1)]51 b = [0 for _ in range(n - 1)]52 53 for i in range(n - 1):54 ai, bi = map(int, input().split())55 ai -= 156 bi -= 157 a[i] = ai58 b[i] = bi59 60 graph[ai].append(bi)61 graph[bi].append(ai)62 63 depth = calc_depth(vertex_count=n, graph=graph)64 65 q = int(input())66 imos = [0 for _ in range(n)]67 68 for i in range(q):69 ti, ei, xi = map(int, input().split())70 ei -= 171 72 va = a[ei]73 vb = b[ei]74 75 if ti == 2:76 va, vb = vb, va77 78 if depth[va] < depth[vb]:79 imos[0] += xi80 imos[vb] -= xi81 else:82 imos[va] += xi83 84 print(*run_imos(graph=graph, depth=depth, imos=imos), sep="\n")85 86 87if __name__ == "__main__":88 main()89