Компоненты сильной связности. Алгоритм Косараю-Шарира
Перейти к навигации
Перейти к поиску
- Упорядочиваем вершины по убыванию времени выхода (как при топологической сортировке).
- Транспонируем граф.
- Обходим вершины транспонированного графа в порядке убывания времени выхода ("порядке топологической сортировки").
vector<vector<int>> graph(vertexCount), graphR(vertexCount);
vector<int> visited(vertexCount);
vector<int> order;
void dfs1(int v) {
visited[v] = 1;
for (int to : graph[v])
if (!visited[to])
dfs1(to);
order.push_back(v);
}
void dfs2(int v, int component) {
visited[v] = component;
for (int to : graphR[v])
if (!visited[to])
dfs2(to, component);
}
for (int v = 0; v < vertexCount; v++)
if (!visited[v])
dfs1(v);
reverse(order.begin(), order.end());
fill(visited.begin(), visited.end(), 0);
int componentCount = 0;
for (int v : order)
if (!visited[v])
dfs2(v, ++componentCount);
Построение конденсации:
unordered_map<int, vector<int>> graph, graphR, graphC;
unordered_set<int> visited;
vector<int> order;
void dfs1(int v) {
visited.insert(v);
for (int to : graph[v])
if (!visited.count(to))
dfs1(to);
order.push_back(v);
}
unordered_map<int, int> scc;
void dfs2(int v, int component) {
visited.insert(v);
scc[v] = component;
for (int to : graphR[v]) {
if (!visited.count(to))
dfs2(to, component);
}
}
int main() {
int vertexCount, edgeCount;
cin >> vertexCount >> edgeCount;
for (int i = 0; i < edgeCount; i++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
graphR[b].push_back(a);
}
for (int v = 0; v < vertexCount; v++)
if (!visited.count(v))
dfs1(v);
reverse(order.begin(), order.end());
visited.clear();
int sccN = 0;
for (int v : order)
if (!visited.count(v))
dfs2(v, sccN++);
for (int v = 0; v < vertexCount; v++)
for (int to : graph[v])
if (scc[v] != scc[to])
graphC[scc[v]].push_back(scc[to]);
}
Ссылки
- e-maxx.ru — Поиск компонент сильной связности, построение конденсации графа
- neerc.ifmo.ru/wiki — Использование обхода в глубину для поиска компонент сильной связности
- algorithmica.org — Продвинутый DFS
- informatics.mccme.ru — Курс «Алгоритмы на графах» — часть 2
- Калинин П. Поиск в глубину
- Лахно А. Поиск в глубину и его применение
- algs4.cs.princeton.edu/lectures — 4.2 Directed Graphs
- VisuAlgo — Graph Traversal
- CodeLibrary — Strongly connected components. Kosaraju's algorithm