Approach
Breadth-first search
For ABC396 E — Min of Restricted Sum, 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
- 77 lines of Python from the credited upstream file abc396_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 main():5 import sys6 from collections import deque7 8 input = sys.stdin.readline9 10 n, m = map(int, input().split())11 graph = [[] for _ in range(n)]12 13 for _ in range(m):14 ai, bi, zi = map(int, input().split())15 ai -= 116 bi -= 117 18 graph[ai].append((bi, zi))19 graph[bi].append((ai, zi))20 21 pending = -122 23 def bfs(start):24 q = deque([start])25 colors[start] = 026 zero_or_one[0].append(start)27 28 while q:29 cur = q.popleft()30 color = colors[cur]31 32 for to, zi in graph[cur]:33 expected_color = color ^ (zi >> digit & 1)34 35 if colors[to] != pending:36 if colors[to] != expected_color:37 return False38 else:39 colors[to] = expected_color40 zero_or_one[expected_color].append(to)41 q.append(to)42 43 return True44 45 ans = [0] * n46 47 48 for digit in range(30):49 colors = [pending] * n50 51 52 for i in range(n):53 if colors[i] != pending:54 continue55 56 57 zero_or_one = [[], []]58 59 if not bfs(i):60 print(-1)61 exit()62 63 64 zero_count, one_count = len(zero_or_one[0]), len(zero_or_one[1])65 66 if zero_count < one_count:67 zero_or_one[0], zero_or_one[1] = zero_or_one[1], zero_or_one[0]68 69 for one_id in zero_or_one[1]:70 ans[one_id] |= 1 << digit71 72 print(*ans)73 74 75if __name__ == "__main__":76 main()77