Kosaraju,但是边双

· · 个人记录

众所周知边双和强联通没有什么本质性的区别,于是我们 dfs 的时候不考虑儿子指向爹的边就可以了。具体而言,第一遍 dfs 不走爹边,第二遍 dfs(注意此时走的是反图)不走树边。

#include <bits/stdc++.h>
using namespace std;
constexpr int N = 5e5 + 9, M = 2e6 + 9;
int n, m, hd[N], tot, col[N], a[N], t, c;
bool vst[N], ontr[M << 1];
vector<int> ans[N];
struct {
  int to, nxt;
} es[M << 1];
void add(int u, int v) { es[++tot] = {v, hd[u]}, hd[u] = tot; }
void dfs1(int x) {
  vst[x] = true;
  for (int i = hd[x], y; i; i = es[i].nxt)
    if (!ontr[i ^ 1] && !vst[y = es[i].to]) ontr[i] = true, dfs1(y);
  a[++t] = x;
}
void dfs2(int x) {
  col[x] = c;
  for (int i = hd[x], y; i; i = es[i].nxt)
    if (!ontr[i] && !col[y = es[i].to]) dfs2(y);
}
signed main() {
  cin.tie(nullptr)->sync_with_stdio(false);
  cin >> n >> m, tot = 1;
  for (int u, v; m; --m) cin >> u >> v, add(u, v), add(v, u);
  for (int i = 1; i <= n; ++i)
    if (!vst[i]) dfs1(i);
  for (int i = n; i; --i)
    if (!col[a[i]]) ++c, dfs2(a[i]);
  cout << c << '\n';
  for (int i = 1; i <= n; ++i) ans[col[i]].push_back(i);
  for (int i = 1; i <= c; ++i) {
    cout << ans[i].size();
    for (int x : ans[i]) cout << ' ' << x;
    cout << '\n';
  }
  return cout << flush, 0;
}

不知道为什么似乎很少有人用的写法。不过边双写法本来也很多就是了。