C++ アルゴリズムとデータ構造のライブラリ
#include "library/graph/connected_components/connected_components.hpp"groups: 連結な頂点群の集合ids : ids[v] := 頂点vが属するgroupsのインデックス$O(V+E)$
auto [groups, ids] = connected_components(G);
#pragma once
#include "library/graph/base/graph.hpp"
pair<vector<vector<int>>, vector<int>> connected_components(const Graph &G) {
int N = G.size(), cnt = 0;
vector<vector<int>> groups;
vector<int> ids(N, -1);
vector<int> com;
auto dfs = [&](auto &f, int v) -> void {
ids[v] = cnt;
com.push_back(v);
for (auto &&[from, to, cost, idx] : G[v]) {
if (ids[to] != -1) continue;
f(f, to);
}
};
for (int i = 0; i < N; ++i) {
if (ids[i] != -1) continue;
com.clear();
dfs(dfs, i);
groups.push_back(com);
++cnt;
}
return {groups, ids};
}#line 2 "library/graph/base/edge.hpp"
struct Edge {
int from, to;
long long cost;
int idx;
Edge(int from, int to, long long cost = 1, int idx = -1)
: from(from), to(to), cost(cost), idx(idx) {}
};
#line 3 "library/graph/base/graph.hpp"
struct Graph {
int N;
vector<vector<Edge>> G;
int es;
Graph() = default;
Graph(int N) : N(N), G(N), es(0) {}
const vector<Edge> &operator[](int v) const { return G[v]; }
int size() const { return N; }
void add(int from, int to, long long cost = 1) {
G[from].push_back(Edge(from, to, cost, es++));
}
void add_both(int from, int to, long long cost = 1) {
G[from].push_back(Edge(from, to, cost, es));
G[to].push_back(Edge(to, from, cost, es++));
}
void read(int M, int padding = -1, bool weighted = false,
bool directed = false) {
for (int i = 0; i < M; i++) {
int u, v;
cin >> u >> v;
u += padding, v += padding;
long long cost = 1ll;
if (weighted) cin >> cost;
if (directed) {
add(u, v, cost);
} else {
add_both(u, v, cost);
}
}
}
};
#line 3 "library/graph/connected_components/connected_components.hpp"
pair<vector<vector<int>>, vector<int>> connected_components(const Graph &G) {
int N = G.size(), cnt = 0;
vector<vector<int>> groups;
vector<int> ids(N, -1);
vector<int> com;
auto dfs = [&](auto &f, int v) -> void {
ids[v] = cnt;
com.push_back(v);
for (auto &&[from, to, cost, idx] : G[v]) {
if (ids[to] != -1) continue;
f(f, to);
}
};
for (int i = 0; i < N; ++i) {
if (ids[i] != -1) continue;
com.clear();
dfs(dfs, i);
groups.push_back(com);
++cnt;
}
return {groups, ids};
}