#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<ctime>
#include<cctype>
#include<string>
#include<algorithm>
#include<iostream>
#define MM 50002
#define NN 10002
using namespace std;
int n,m,cnt,sign,top,tot;
int stack[MM],low[NN],first[NN],dfn[NN],belong[NN],outdegree[NN],num[NN];
bool vis[NN];
struct node{
int next,from,to;
}edge[MM];
inline void addedge(int x,int y){
sign++;
edge[sign].from=x;
edge[sign].to=y;
edge[sign].next=first[x];
first[x]=sign;
}
inline void tarjan(int x){
cnt++;
low[x]=dfn[x]=cnt;
top++;
stack[top]=x;
vis[x]=1;
for (int i=first[x];i!=0;i=edge[i].next){
int v=edge[i].to;
if (!dfn[v]){
tarjan(v);
low[x]=min(low[x],low[v]);
}
else if (vis[v]) low[x]=min(low[x],dfn[v]);
}
if (dfn[x]==low[x]){
tot++;
int v=-1;
while (v!=x){
v=stack[top];
top--;
belong[v]=tot;
num[tot]++;
vis[v]=0;
}
}
}
int main(){
freopen("cow.in","r",stdin);
cin>>n>>m;
for (int i=1;i<=m;i++){
int x,y;
cin>>x>>y;
addedge(x,y);
}
for (int i=1;i<=n;i++)
if (!dfn[i])
tarjan(i);
for (int i=1;i<=m;i++)
if (belong[edge[i].from]!=belong[edge[i].to])
outdegree[belong[edge[i].from]]++;
int sum=0,x;
for (int i=1;i<=tot;i++)
if (outdegree[i]==0){
sum++;
x=i;
}
if (sum==1) cout<<num[x];
else cout<<"0";
return 0;
}
STEP 1:单向建边
inline void addedge(int x,int y){
sign++;
edge[sign].from=x;
edge[sign].to=y;
edge[sign].next=first[x];
first[x]=sign;
}
STEP 2:tarjan遍历每一个点,每个点只会遍历一次,且只会退一次栈,因为一个点只能在一个强连通分量内存在
注意:
当V在栈中时,low[x]=min(low[x],dfn[v]);
当V不在栈中时,low[x]=min(low[x],low[v]);
inline void tarjan(int x){
cnt++;
dfn[x]=low[x]=cnt;
top++;
stack[top]=x;
vis[x]=1;
for (int i=first[x];i!=0;i=edge[i].next){
int v=edge[i].to;
if (!dfn[v]){
tarjan(v);
low[x]=min(low[x],low[v]);
}
else if (vis[v]) low[x]=min(low[x],dfn[v]);
}
if (low[x]==dfn[x]){
tot++;
int v=-1;
while (v!=x){
v=stack[top];
top--;
belong[v]=tot;
num[tot]++;
vis[v]=0;
}
}
}
STEP 3:查找每个强连通的出度
for (int i=1;i<=m;i++)
if (belong[edge[i].from]!=belong[edge[i].to])
outdegree[belong[edge[i].from]]++;
STEP 4 : 当且仅当只有一个出度为1的强连通分量时存在答案,且答案为此强连通分量中牛的个数
for (int i=1;i<=tot;i++)
if (outdegree[i]==0){
sum++;
x=i;
}
if (sum==1) cout<<num[x];
else cout<<"0";
return 0;