Approach
Breadth-first search
For ABC222 E — Red and Blue Tree, 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
- 86 lines of Python from the credited upstream file abc222_e.py.
- The implementation visibly relies on sequence storage, ordered lookup, work queue, cached states.
- 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 main():5 import sys6 from collections import deque7 8 input = sys.stdin.readline9 10 n, m, k = map(int, input().split())11 a = list(map(int, input().split()))12 graph = [[] for _ in range(n)]13 14 for i in range(n - 1):15 ai, bi = map(int, input().split())16 ai -= 117 bi -= 118 19 20 graph[ai].append((bi, i))21 graph[bi].append((ai, i))22 23 24 count = [0] * (n - 1)25 26 27 28 def bfs(start):29 inf = -130 dist = [inf] * n31 dist[start] = 032 q = deque([start])33 34 while q:35 qi = q.popleft()36 37 for to, _ in graph[qi]:38 if dist[to] != inf:39 continue40 41 dist[to] = dist[qi] + 142 q.append(to)43 44 return dist45 46 for start, goal in zip(a, a[1:]):47 start -= 148 goal -= 149 50 dist = bfs(start)51 cur = goal52 53 54 while cur != start:55 for to, edge_id in graph[cur]:56 if dist[to] < dist[cur]:57 cur = to58 count[edge_id] += 159 60 break61 62 63 64 r = k + sum(count)65 66 if r < 0 or r % 2 == 1:67 print(0)68 exit()69 70 71 r = 272 dp = [0] * (r + 1)73 dp[0] = 174 mod = 99824435375 76 for ci in count:77 for i in range(r - ci, -1, -1):78 dp[i + ci] += dp[i]79 dp[i + ci] %= mod80 81 print(dp[r])82 83 84if __name__ == "__main__":85 main()86