Tarjan 模板

· · 个人记录

#include <iostream>
#include <set>

using namespace std;

const int MaxN = 2e4 + 10;

int scc[MaxN], s[MaxN], a[MaxN], low[MaxN], dfn[MaxN], cnt, tot, sz, n, m;
set<int> g[MaxN], e[MaxN];

void DFS(int x) {
  if (dfn[x]) {
    return;
  }
  s[++tot] = x;
  low[x] = dfn[x] = ++cnt;
  for (int i : g[x]) {
    if (!dfn[i]) {
      DFS(i);
      low[x] = min(low[x], low[i]);       // 访问过
    } else if (dfn[i] && dfn[i] != -1) {  // 未访问过
      low[x] = min(low[x], dfn[i]);       // 尚在栈中
    }
  }
  if (low[x] == dfn[x]) {
    sz++;
    while (s[tot] != x) {
      scc[s[tot]] = sz;
      e[sz].insert(s[tot]);
      dfn[s[tot--]] = -1;
    }
    scc[s[tot]] = sz;
    e[sz].insert(s[tot]);
    dfn[s[tot--]] = -1;
  }
}

int main() {
  cin >> n >> m;
  for (int i = 1, x, y; i <= m; i++) {
    cin >> x >> y;
    g[x].insert(y);
  }
  for (int i = 1; i <= n; i++) {
    DFS(i);
  }
  for (int i = 1; i <= sz; i++) {
    a[*e[i].begin()] = i;
  }
  cout << sz << endl;
  for (int i = 1; i <= n; i++) {
    if (a[i]) {
      for (int j : e[a[i]]) {
        cout << j << " ";
      }
      cout << endl;
    }
  }
  return 0;
}