DSA · Competitive Programmer · Pattern 6 of 9
Graph Theory (MST, SCC, Bridges)
13 problems.
Your progress0%
- 1st Visit
- 0/13
- 2nd Visit
- 0/13
- Revise
- 0/13
About this pattern
This pattern covers graph algorithms beyond traversal. A minimum spanning tree connects every vertex at the least total cost: Kruskal sorts the edges and joins components with a DSU in O(E log E), while Prim suits dense graphs. Strongly connected components, found with Tarjan's or Kosaraju's algorithm, group vertices that reach each other in a directed graph, and condensing them leaves a DAG. Bridges and articulation points, found with DFS discovery times and low-links, are the edges or vertices whose removal disconnects the graph. Signals: connecting everything at minimum cost, mutual reachability, critical links, or a virtual vertex that simplifies costs. All of these run in near-linear time.
// Bridges with Tarjan low-links; adj[u] holds {v, edgeId}; tin starts at -1
vector<vector<pair<int, int>>> adj;
vector<int> tin, low;
vector<pair<int, int>> bridges;
int timer_ = 0;
void dfs(int u, int parentEdge) {
tin[u] = low[u] = timer_++;
for (auto [v, id] : adj[u]) {
if (id == parentEdge) continue;
if (tin[v] != -1) low[u] = min(low[u], tin[v]); // back edge
else {
dfs(v, id);
low[u] = min(low[u], low[v]);
if (low[v] > tin[u]) bridges.push_back({u, v});
}
}
}