Analysis of the Bridge-Finding Algorithm
The function magic() appears to be attempting to find bridges in an undirected graph using a depth-first search (DFS) approach. Typically, bridge-finding algorithms use two separate arrays:
- A discovery time array (
dfn[])
- A low-link value array (
low[])
This implementation instead uses a single array v[] for both purposes. Let's analyze if this can work correctly.
Understanding the Implementation
int magic(int prevedge) {
int curr = edge[prevedge].dest, vlow;
if (v[curr]) return v[curr]; // If already visited, return current value
v[curr] = vlow = ++vtop; // Initialize with discovery time
for (int e = head[curr], vtmp; e; e = edge[e].next)
if (e != (prevedge ^ 1)) { // Skip the parent edge
vtmp = magic(e); // Recursive call
if (v[curr] < vtmp) be[++btop] = e; // Bridge detection
if (vtmp < vlow) vlow = vtmp; // Update low value
}
return v[curr] = vlow; // Update and return low value
}
The key insight is that the function:
- Initially sets
v[curr] to a discovery time
- During exploration, identifies bridges when
v[curr] < vtmp
- After exploration, updates
v[curr] to the minimum reachable value
- Returns this updated value
Correctness Analysis
This approach is actually correct despite using only one array. Here's why:
- The bridge detection (
v[curr] < vtmp) happens before v[curr] is updated to its low value
- When we visit an already visited node, we get its current value from
v[], which might be:
- Its original discovery time (if we're still exploring its subtree)
- Its updated low value (if its exploration is complete)
Either way, this correctly represents the lowest discovery time reachable from that node, which is what we need for bridge detection.
Example Where It Works Correctly
Consider a graph with nodes 1-4, with edges (1,2), (2,3), (3,4), (4,2):
- Nodes 2,3,4 form a cycle
- Edge (1,2) is a bridge
When DFS starts from node 1:
v[1] = 1
- Visit node 2:
v[2] = 2
- Visit node 3:
v[3] = 3
- Visit node 4:
v[4] = 4
- Revisit node 2: Return
v[2] = 2
- Update
v[4] = 2
- Update
v[3] = 2
- Update
v[2] = 2 (remains unchanged)
- Compare
v[1] = 1 with returned value 2 → Edge (1,2) is correctly identified as a bridge
Conclusion
While counterintuitive, this single-array implementation correctly identifies bridges. The key is that bridge detection occurs during the DFS exploration phase, before node values are updated to their final low values. This approach saves memory but might be harder to understand than the traditional two-array method.