如何高效验证有向图中各顶点的最短路径估计值d[v]?
Great question! Comparing against a full Bellman-Ford run is indeed overkill here—we can validate the given d[v] values in O(V + E) time (linear time, much faster than Bellman-Ford's O(VE)) by leaning on core shortest path properties. Here's a step-by-step breakdown:
Step 1: Check Non-Negotiable Invariants
First, confirm two necessary conditions (if either fails, the d[v] values are definitely invalid):
- Source Vertex Check: Ensure
d[s] == 0—unlesssis part of a reachable negative cycle. Ifsis in a negative cycle,d[s]must be-∞(since there's no finite shortest path fromsto itself). - Triangle Inequality for All Edges: For every directed edge
u → vwith weightw, verify thatd[v] ≤ d[u] + w. This is the core property of shortest paths: taking any edge fromutovcan't give a shorter path tovthan the givend[v]. If any edge violates this, you can immediately conclude thed[v]values are wrong.
Step 2: Validate Reachability and Negative Cycle Consistency
Passing Step 1 tells us d[v] is a valid lower bound for the shortest path from s to v, but we need to make sure it's the tightest possible bound (or correctly marked as -∞ for vertices with no finite shortest path):
- Build the Equality Subgraph: Create a subgraph
Hthat includes only edges whered[v] == d[u] + w. These edges represent potential shortest path edges—ifd[v]is valid, there must be a path fromstovusing only these edges. - Check Finite Distances: For every vertex
vwith a finited[v]:- Run a BFS or DFS starting from
sonH—ifvisn't reachable via this subgraph, there's no path whose total weight equalsd[v], so the given distance is invalid.
- Run a BFS or DFS starting from
- Check Infinite (Negative) Distances: For every vertex
vmarked withd[v] == -∞:- First,
vmust be reachable fromsin the original graphG(if it's not reachable,d[v]should be∞, not-∞). - Second,
vmust be able to reach a negative cycle inG(since only then can you loop the cycle infinitely to get arbitrarily small distances). To verify this efficiently:- Use BFS/DFS on
Gto find all vertices reachable froms(call this setR). - Build the reverse graph
G'(flip all edge directions). - Find all vertices in
Gthat are part of a negative cycle (run Bellman-Ford once ons—vertices that can still be relaxed afterV-1iterations are in or can reach a negative cycle). - Run BFS/DFS on
G'from these negative cycle vertices to find all vertices that can reach a negative cycle. Anyvmarked-∞must be in this set and inR; conversely, any vertex in both sets must be marked-∞.
- Use BFS/DFS on
- First,
Why This Is Better Than Bellman-Ford
Bellman-Ford computes all shortest paths from scratch, which is O(VE). This approach, by contrast, leverages the given d[v] values to skip redundant computations, resulting in linear time complexity—perfect for large graphs where Bellman-Ford would be too slow.
内容的提问来源于stack exchange,提问作者Ori Netanel Ben-Zaken

