#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <stdlib.h>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
#include <set>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef long long LL;
const int inf = 1<<30;
const LL maxn = 50010;
int N, M, ecnt = 1, head[maxn];
struct node{
int v, next;
}es[maxn];
void addEdge(int u, int v){
es[ecnt].v = v, es[ecnt].next = head[u];
head[u] = ecnt++;
}
int indx = 0, scc = 0;
bool ins[maxn];
int dfn[maxn], low[maxn], belong[maxn];
stack<int> s;
void tarjan(int u){
int v;
dfn[u] = low[u] = ++indx;
s.push(u);
ins[u] = true;
for(int i = head[u]; i != -1; i = es[i].next){
v = es[i].v;
if(!dfn[v]){
tarjan(v);
low[u] = min(low[u], low[v]);
}
else if(ins[v])
low[u] = min(low[u], dfn[v]);
}
if(dfn[u] == low[u]){
++scc;
do{
v = s.top();
s.pop();
ins[v] = false;
belong[v] = scc;
}while(u!=v);
}
}
int out[maxn], in[maxn];
int main()
{
int a, b;
ms(head, -1);
cin >> N >> M;
for(int i = 1; i <= M; ++i){
cin >> a >> b;
addEdge(a, b);
}
for(int i = 1; i <= N; ++i){
if(!dfn[i])
tarjan(i);
}
for(int u = 1; u <= N; ++u){
for(int i = head[u]; i != -1; i = es[i].next){
int v = es[i].v;
if(belong[u] != belong[v])
++out[belong[u]], ++in[belong[u]];
}
}
int cnt = 0, ans = 0, tag;
for(int i = 1; i <= scc; ++i)
if(out[i]==0)
++cnt, tag = i;
if(cnt!=1) cout << "0" << endl;
else{
for(int i = 1; i <= N; ++i)
if(belong[i] == tag)
++ans;
cout << ans << endl;;
}
return 0;
}
强连通分量缩点 POJ 2186
最新推荐文章于 2023-06-05 21:27:11 发布