Official

E - Nearest Black Vertex Editorial by en_translator


We precalculate the distance between every pair of vertices for later reference. This can be achieved by a Breadth-First Search (BFS) in an \(O(N+M)\) time for each starting point, for a total of \(O(N(N+M))\) time for all starting points.

“The minimum distance from vertex \(v\) to a black vertex is exactly \(d\)” if and only if “there is a black vertex whose distance from vertex \(v\) is less than or equal to \(d\)” and “there is a black vertex whose distance from vertex \(v\) is strictly less than \(d\).” Thus , the two conditions in the Problem Statement are equivalent to the following three:

  1. There is at least one black vertex.
  2. For all \(i = 1, 2, \ldots, K\), “there is a black vertex whose distance from vertex \(p_i\) is less than or equal to \(d_i\).”
  3. For all \(i = 1, 2, \ldots, K\), “there is a black vertex whose distance from vertex \(p_i\) is strictly less than \(d_i\).”

The third condition is satisfied if and only if every vertex, whose distance from vertex \(p_i\) is strictly less than \(d_i\) for at least one \(i = 1, 2, \ldots, K\), is painted white.

All that left is to determine the paintings of the remaining vertices to satisfy the first and second conditions. However, these two conditions both claim an existence of a black vertex, so it is optimal to paint all other vertices black.

In conclusion, the optimal painting is to paint white every vertex whose distance from vertex \(p_i\) is strictly less than \(d_i\) for at least one \(i = 1, 2, \ldots, K\), and paint the other vertices black. If that “optimal” painting actually satisfies the condition, then print Yes and that painting; otherwise, print No. This way, your code will be accepted.

posted:
last update: