其实是给自己的一篇分享打个小广告。
Tarjan算法的简要证明
https://www.acwing.com/blog/content/1819/
代码和y总的差不多
#include <bits/stdc++.h>
using namespace std;
const int N = 10010;
const int M = 50010;
int h[N], e[M], ne[M], idx;
int n, m;
stack<int> stk;
bool in_stk[N];
int id[N], timestamp;
int scc_cnt, scc_size[N];
int deg_out[N];
int dfn[N], low[N];
void add(int a, int b){
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++;
}
void tarjan(int u){
low[u] = dfn[u] = ++ timestamp;
stk.push(u);
in_stk[u] = true;
for(int i = h[u]; ~i; i = ne[i]){
int j = e[i];
if(!dfn[j]){
tarjan(j);
low[u] = min(low[u], low[j]);
}
else if(in_stk[j]){
low[u] = min(low[u], low[j]);
}
}
if(dfn[u] == low[u]){
int y;
++ scc_cnt;
do {
y = stk.top();
stk.pop();
id[y] = scc_cnt;
in_stk[y] = false;
scc_size[scc_cnt] ++;
} while(y != u);
}
}
int main(){
memset(h, -1, sizeof h);
cin >> n >> m;
while(m --){
int a, b;
cin >> a >> b;
add(a, b);
}
for(int i = 1; i <= n; i ++){
if(!dfn[i]) tarjan(i);
}
for(int i = 1; i <= n; i ++){
for(int j = h[i]; ~j; j = ne[j]){
int k = e[j];
int a = id[i];
int b = id[k];
if(a != b){
deg_out[a] ++;
}
}
}
int sum = 0;
int zeros = 0;
for(int i = 1; i <= scc_cnt; i ++){
if(!deg_out[i]){
zeros ++;
sum += scc_size[i];
if(zeros > 1){
sum = 0;
break;
}
}
}
cout << sum << endl;
return 0;
}