tarjan算法学习过程中必做的一道板子题。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <stack>
#include <queue>
using namespace std;
//Mystery_Sky
//
#define maxn 1000010
#define INF 0x3f3f3f3f
struct Edge{
int to;
int next;
}edge[maxn];
stack <int> st;
int low[maxn], dfn[maxn], vis[maxn];
int head[maxn], cnt;
int scc, ans, tot, num[maxn];
int n, m, u, v;
inline void add_edge(int u, int v)
{
edge[++cnt].to = v;
edge[cnt].next = head[u];
head[u] = cnt;
}
void tarjan(int u)
{
dfn[u] = low[u] = ++tot;
st.push(u);
vis[u] = 1;
for(int i = head[u]; i; i = edge[i].next) {
int v = edge[i].to;
if(!dfn[v]) {
tarjan(v);
low[u] = min(low[u], low[v]);
}
else if(vis[v]) low[u] = min(low[u], dfn[v]);
}
if(dfn[u] == low[u]) {
int j;
scc++;
do {
j = st.top();
st.pop();
vis[j] = 0;
num[scc]++;
} while(j != u);
}
}
int main() {
scanf("%d%d", &n, &m);
for(int i = 1; i <= m; i++) {
scanf("%d%d", &u, &v);
add_edge(u, v);
}
for(int i = 1; i <= n; i++)
if(!dfn[i]) tarjan(i);
for(int i = 1; i <= scc; i++) {
if(num[i] > 1) ans++;
}
printf("%d
", ans);
return 0;
}