Approach
Breadth-first search
For ABC299 E — Nearest Black Vertex, 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
- 102 lines of Python from the credited upstream file abc299_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 bfs(vertex_count: int, source: int, graph):5 from collections import deque6 7 d = deque()8 d.append(source)9 visited = [False] * vertex_count10 inf = 10 ** 1811 dist = [inf] * vertex_count12 dist[source] = 013 14 while d:15 cur = d.popleft()16 17 if visited[cur]:18 continue19 20 visited[cur] = True21 22 for to in graph[cur]:23 if visited[to]:24 continue25 26 dist[to] = min(dist[to], dist[cur] + 1)27 d.append(to)28 29 return dist30 31 32def main():33 import sys34 35 input = sys.stdin.readline36 37 n, m = map(int, input().split())38 graph = [[] for _ in range(n)]39 40 for _ in range(m):41 ai, bi = map(int, input().split())42 ai -= 143 bi -= 144 45 46 graph[ai].append(bi)47 graph[bi].append(ai)48 49 50 51 k = int(input())52 dist = list()53 pd = list()54 55 none, white, black = -1, 0, 156 colors = [none] * n57 58 for _ in range(k):59 pi, di = map(int, input().split())60 pi -= 161 62 63 d = bfs(vertex_count=n, source=pi, graph=graph)64 dist.append(d)65 pd.append((pi, di))66 67 for j, dij in enumerate(d):68 if dij < di:69 colors[j] = white70 71 count = 072 73 for i, color in enumerate(colors):74 if color == none:75 colors[i] = black76 count += 177 78 if count == 0:79 print("No")80 exit()81 82 inf = 10 ** 1883 84 85 for i, (pi, di) in enumerate(pd):86 d_min = inf87 88 for j, (color, dij) in enumerate(zip(colors, dist[i])):89 if color == black:90 d_min = min(d_min, dij)91 92 if d_min != di:93 print("No")94 exit()95 96 print("Yes")97 print(''.join(map(str, colors)))98 99 100if __name__ == "__main__":101 main()102