题意:有n个奶牛,m条关系,每条关系A,B表示奶牛A喜欢奶牛B,若是有A喜欢B,B喜欢C,则有A喜欢C,现在问被其余n-1头奶牛喜欢的奶牛有多少个。
思路:可能存在环,所以我们先缩点,这样的话就变成一个有向无环的新图,根据这个性质,那么没有出度的点即为答案了,因为若是有出度的点为答案那么其余点必也有边指向它,那么通过缩点能缩成一个点,所以没有出度的点即为答案,但是没有出度的点只能有一个解才合法。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<queue>
#include<deque>
using std::min;
#define ll long long
#define PI acos(-1)
#define INF 0x3f3f3f3f
#define NUM 500020
#define debug true
#define lowbit(x) ((-x)&x)
#define ffor(i,d,u) for(int i=(d);i<=(u);++i)
#define _ffor(i,u,d) for(int i=(u);i>=(d);--i)
#define mst(array,Num,Kind,Count) memset(array,Num,sizeof(Kind)*(Count))
const int P = 1e9+7;
int n,m;
struct edge
{
int f,to,next;
}e[NUM];
int h[NUM/5]={},dfn[NUM/5],low[NUM/5],check[NUM/5]={},depth = 0;
int s = 0,index[NUM/5],snum[NUM/5]={},sta[NUM/5],top = 0;
bool out[NUM/5]={};
int ans;
template <typename T>
void read(T& x)
{
x=0;
char c;T t=1;
while(((c=getchar())<'0'||c>'9')&&c!='-');
if(c=='-'){t=-1;c=getchar();}
do(x*=10)+=(c-'0');while((c=getchar())>='0'&&c<='9');
x*=t;
}
template <typename T>
void write(T x)
{
int len=0;char c[21];
if(x<0)putchar('-'),x*=(-1);
do{++len;c[len]=(x%10)+'0';}while(x/=10);
_ffor(i,len,1)putchar(c[i]);
}
void tarjan(int vertex)
{
int x;
dfn[vertex] = low[vertex] = ++depth;
sta[top] = vertex,++top;
check[vertex] = 1;
for(int i=h[vertex];i!=0;i=e[i].next)
{
x = e[i].to;
if(check[x] == 2)continue;
if(!check[x])
{
tarjan(x);
low[vertex] = min(low[vertex],low[x]);
}
else
low[vertex] = min(low[vertex],dfn[x]);
}
if(low[vertex] == dfn[vertex])
{
++s;
do
{
x = sta[top-1];
index[x] = s;
check[x] = 2;
++snum[s],--top;
}while(x != vertex);
}
}
inline void AC()
{
int x,y;
read(n),read(m);
ffor(i,1,m)
{
read(x),read(y);
e[i].f = x,e[i].to = y,e[i].next = h[x],h[x] = i;
}
ffor(i,1,n)if(!check[i])tarjan(i);
ffor(i,1,m)
{
int fx = index[e[i].f],fy = index[e[i].to];
if(fx != fy)out[fx] = true;
}
int flag = 0;
ffor(i,1,s)if(!out[i])++flag,ans = snum[i];
if(flag > 1)puts("0");
else write(ans),putchar('\n');
}
int main()
{
AC();
return 0;
}