Five graph problems rated 2,000 to 2,200 about loops, links that cannot fail and hubs that cannot close. The move: one depth-first search with discovery times and low links answers every one of them.
This tent holds five problems rated 2,000 to 2,200. Each asks what survives a failure in a graph of up to 10^5 nodes.
Which services restart together? Can a link fail without splitting the network? Which hub splits it when it closes? How many lanes make every single failure harmless?
The first solution removes each part and searches again. It is correct, and it costs one search for every part.
| Problem | The literal route | Its size at the limits |
|---|---|---|
| Services that must restart together | search from every service | 2 × 10^10 steps |
| The richest chain of shares | try every walk through the loops | exponential, without the groups |
| Links the live stream cannot lose | remove each link, search again | 2 × 10^10 steps |
| Groups left when a hub closes | remove each hub, search again | 2 × 10^10 steps |
| Lanes to add so no single lane matters | remove each lane, search again | 6 × 10^10 steps |
One search with two numbers per node replaces all of them.
Exercise · Predict the output: Low links and bridges. The graph has the links 0-1, 1-2, 2-0 and 2-3. A depth-first search from node 0 records disc, the order in which nodes are found, and low, the earliest disc its subtree can reach. A link to a child is a bridge when low of the child is above disc of its parent. What does this print: the low of nodes 0 to 3, then the number of bridges?
adj = [[1, 2], [0, 2], [1, 0, 3], [2]]
disc = [-1] * 4
low = [0] * 4
clock = 0
bridges = 0
def dfs(v, parent):
global clock, bridges
disc[v] = low[v] = clock
clock += 1
for u in adj[v]:
if u == parent:
continue
if disc[u] == -1:
dfs(u, v)
low[v] = min(low[v], low[u])
if low[u] > disc[v]:
bridges += 1
else:
low[v] = min(low[v], disc[u])
dfs(0, -1)
print(*low, bridges)A depth-first search finds each node once, in an order. For every node it keeps two numbers. The first is disc, the time the node was found. The second is low, the earliest disc that its subtree can reach with one link going back up the tree.
Run one depth-first search that records, for each node, when it was found and the earliest node its subtree can reach. The comparison of those two numbers decides the question.
The tests are short. A link from u to its child v is a bridge when low[v] > disc[u]: nothing below v reaches u or above. A hub u is a cut point when some child v has low[v] >= disc[u]. A node v is the root of a strongly connected group when low[v] equals disc[v], and the group is the nodes on a stack above it.
The cut point test needs one care. The root of the search has nothing above it, so it is a cut point only when it has two or more children.
A bridge is a link whose child's low link is above the parent's discovery time: nothing in the child's subtree reaches back.
Exercise · Find the bug: The cycle that looks like a bridge. After a search, parent[v] is the parent of v in the search tree, or -1 for the root. This counts the bridges: the links from a parent to a child whose subtree cannot reach the parent or above. Which line is wrong?
def count_bridges(disc, low, parent):
count = 0
for v in range(len(disc)):
if parent[v] != -1 and low[v] >= disc[parent[v]]:
count += 1
return countThe Academy lessons Graph traversal and Cycles and bipartite gave you the search and the test for a cycle. Topological sort ordered a graph without loops, and Graphs gave you the lists. This tent asks which parts of a graph carry the connections.
Three more ideas stand on the low link. Strongly connected groups collapse a graph with loops into one without, and the longest chain then follows the topological order of the groups. Bridges split a graph into two-edge-connected groups.
The fewest lanes to add is half the leaves of the tree of those groups, rounded up. Repeated links need care. A second link between the same two nodes is a cycle, so skip only the link you came by, not every link to the parent.
The cut point test has its own trap, at the root.
The root of the search is a cut point only with two or more children; the plain low-link test wrongly marks a root with one child.
Exercise · Break it: The hub at the start of the search. Nodes are numbered from 0, and the links go both ways. This counts the hubs whose closing splits the network. It marks a node when some child of it in the search tree has low at least the disc of the node. Find an input where it is wrong.
def count_hubs(n, links):
adj = [[] for _ in range(n)]
for a, b in links:
adj[a].append(b)
adj[b].append(a)
disc = [-1] * n
low = [0] * n
state = {"clock": 0}
hubs = set()
def dfs(v, parent):
disc[v] = low[v] = state["clock"]
state["clock"] += 1
for u in adj[v]:
if u == parent:
continue
if disc[u] == -1:
dfs(u, v)
low[v] = min(low[v], low[u])
if low[u] >= disc[v]:
hubs.add(v)
else:
low[v] = min(low[v], disc[u])
dfs(0, -1)
return len(hubs)| Limit | What it tells you |
|---|---|
| 10^5 nodes, up to 2 × 10^5 links | one search in O(n + m): about 3 × 10^5 steps |
| a path of 10^5 nodes | the search must be iterative: no recursion |
| repeated links | skip the link you arrived by (its number), not every link to the parent |
| two-way and one-way links | bridges and cut points are for two-way links, strongly connected groups for one-way |
| a tree of groups with L leaves | the lanes to add are the ceiling of L / 2, and 0 when there is one group |
The full treatment is in Fast I/O and stress testing. The code below counts the bridges with an explicit stack. Each link has two directed copies, numbered 2i and 2i + 1, so a repeated link is told apart from the link the search came by.
import sys
def main():
data = sys.stdin.buffer.read().split()
n, m = int(data[0]), int(data[1])
head = [-1] * n
nxt = [0] * (2 * m)
to = [0] * (2 * m)
for i in range(m):
a, b = int(data[2 + 2 * i]) - 1, int(data[3 + 2 * i]) - 1
to[2 * i], nxt[2 * i], head[a] = b, head[a], 2 * i
to[2 * i + 1], nxt[2 * i + 1], head[b] = a, head[b], 2 * i + 1
disc = [-1] * n
low = [0] * n
cur = head[:]
via = [-1] * n
clock = 0
bridges = 0
for s in range(n):
if disc[s] != -1:
continue
disc[s] = low[s] = clock
clock += 1
stack = [s]
while stack:
v = stack[-1]
e = cur[v]
if e != -1:
cur[v] = nxt[e]
if via[v] != -1 and e >> 1 == via[v] >> 1:
continue
u = to[e]
if disc[u] == -1:
disc[u] = low[u] = clock
clock += 1
via[u] = e
stack.append(u)
else:
low[v] = min(low[v], disc[u])
else:
stack.pop()
if stack:
p = stack[-1]
low[p] = min(low[p], low[v])
if low[v] > disc[p]:
bridges += 1
sys.stdout.write(str(bridges) + "\n")
main()import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
int m = (int) in.nval;
int[] head = new int[n], nxt = new int[2 * m], to = new int[2 * m];
Arrays.fill(head, -1);
for (int i = 0; i < m; i++) {
in.nextToken();
int a = (int) in.nval - 1;
in.nextToken();
int b = (int) in.nval - 1;
to[2 * i] = b; nxt[2 * i] = head[a]; head[a] = 2 * i;
to[2 * i + 1] = a; nxt[2 * i + 1] = head[b]; head[b] = 2 * i + 1;
}
int[] disc = new int[n], low = new int[n], cur = head.clone(), via = new int[n];
Arrays.fill(disc, -1);
Arrays.fill(via, -1);
int clock = 0, bridges = 0;
int[] stack = new int[n];
for (int s = 0; s < n; s++) {
if (disc[s] != -1) continue;
disc[s] = low[s] = clock++;
int top = 0;
stack[top++] = s;
while (top > 0) {
int v = stack[top - 1];
int e = cur[v];
if (e != -1) {
cur[v] = nxt[e];
if (via[v] != -1 && (e >> 1) == (via[v] >> 1)) continue;
int u = to[e];
if (disc[u] == -1) {
disc[u] = low[u] = clock++;
via[u] = e;
stack[top++] = u;
} else {
low[v] = Math.min(low[v], disc[u]);
}
} else {
top--;
if (top > 0) {
int p = stack[top - 1];
low[p] = Math.min(low[p], low[v]);
if (low[v] > disc[p]) bridges++;
}
}
}
}
System.out.println(bridges);
}
}#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<int> head(n, -1), nxt(2 * m), to(2 * m);
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
a--;
b--;
to[2 * i] = b; nxt[2 * i] = head[a]; head[a] = 2 * i;
to[2 * i + 1] = a; nxt[2 * i + 1] = head[b]; head[b] = 2 * i + 1;
}
vector<int> disc(n, -1), low(n, 0), cur = head, via(n, -1);
int clockTick = 0, bridges = 0;
vector<int> stack;
for (int s = 0; s < n; s++) {
if (disc[s] != -1) continue;
disc[s] = low[s] = clockTick++;
stack.push_back(s);
while (!stack.empty()) {
int v = stack.back();
int e = cur[v];
if (e != -1) {
cur[v] = nxt[e];
if (via[v] != -1 && (e >> 1) == (via[v] >> 1)) continue;
int u = to[e];
if (disc[u] == -1) {
disc[u] = low[u] = clockTick++;
via[u] = e;
stack.push_back(u);
} else {
low[v] = min(low[v], disc[u]);
}
} else {
stack.pop_back();
if (!stack.empty()) {
int p = stack.back();
low[p] = min(low[p], low[v]);
if (low[v] > disc[p]) bridges++;
}
}
}
}
cout << bridges << "\n";
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0], m = data[1];
const head = new Array(n).fill(-1);
const nxt = new Array(2 * m).fill(0);
const to = new Array(2 * m).fill(0);
for (let i = 0; i < m; i++) {
const a = data[2 + 2 * i] - 1, b = data[3 + 2 * i] - 1;
to[2 * i] = b; nxt[2 * i] = head[a]; head[a] = 2 * i;
to[2 * i + 1] = a; nxt[2 * i + 1] = head[b]; head[b] = 2 * i + 1;
}
const disc = new Array(n).fill(-1);
const low = new Array(n).fill(0);
const cur = head.slice();
const via = new Array(n).fill(-1);
let clock = 0, bridges = 0;
for (let s = 0; s < n; s++) {
if (disc[s] !== -1) continue;
disc[s] = low[s] = clock++;
const stack = [s];
while (stack.length) {
const v = stack[stack.length - 1];
const e = cur[v];
if (e !== -1) {
cur[v] = nxt[e];
if (via[v] !== -1 && (e >> 1) === (via[v] >> 1)) continue;
const u = to[e];
if (disc[u] === -1) {
disc[u] = low[u] = clock++;
via[u] = e;
stack.push(u);
} else {
low[v] = Math.min(low[v], disc[u]);
}
} else {
stack.pop();
if (stack.length) {
const p = stack[stack.length - 1];
low[p] = Math.min(low[p], low[v]);
if (low[v] > disc[p]) bridges++;
}
}
}
}
process.stdout.write(bridges + "\n");On the sample with 5 nodes and the 5 links 1 2, 2 3, 3 1, 3 4 and 4 5, all four programs print 2: the links 3-4 and 4-5.
The slow twin removes each link in turn and counts the groups again with a union find. It shares no low link with the fast code.
import random
from fast import count_bridges
from slow import count_bridges as slow_bridges
for seed in range(1000):
rng = random.Random(seed)
n = rng.randint(1, 7)
links = [[rng.randrange(n), rng.randrange(n)] for _ in range(rng.randint(0, 9))]
links = [l for l in links if l[0] != l[1]]
if count_bridges(n, links) != slow_bridges(n, links):
print("different at", n, links)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Use low[v] >= disc[parent] in place of the strict test, and seed 0 fails. For 7 nodes and 6 links it counts 3 bridges where there are 2.
At 2,000 to 2,200 the search is known, and the work is the test and the edge cases. Watch for repeated links, the root, and the path of 10^5 nodes. Write which test decides the question in one line before you code. Aim for about 50 minutes a problem, and keep 10 for the stress test on graphs of up to 7 nodes.
The first two use one-way links: groups, then the best chain over them. The three after use two-way links: bridges, cut points, and the lanes that make every single failure harmless, which is the problem rated 2,200.
For each problem, write which low-link test decides it, in one line. Then write the slow twin that removes parts and searches again, and stress test on up to 7 nodes.
Checkpoint · Graphs, SCC and bridges
Q1/5 What does low[v] hold after a depth-first search?
Answer: B
Comparing low[v] with disc[u], for the parent u, decides whether the link from u to v is a bridge.
Q2/5 For the links 0-1, 1-2, 2-0 and 2-3, how many bridges are there?
Answer: B
Only 2-3 is a bridge. The triangle 0, 1, 2 has a cycle through each of its links, so none of them is a bridge.
Q3/5 A triangle is tested with low[v] >= disc[parent] instead of the strict test. How many bridges does it report?
Answer: B
The link from node 0 to node 1 has low[1] equal to disc[0], which the >= test counts. A bridge needs the subtree to stay strictly below the parent.
Q4/5 When is the root of the search a cut point?
Answer: C
The root has nothing above it. For the path 0, 1, 2 the root has one child, so only node 1 is a cut point.
Q5/5 Why is the search written with an explicit stack in these problems?
Answer: B
Python stops at about 1,000 nested calls by default. An explicit stack and a pointer into each node's list have no depth limit.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.