Every cow’s dream is to become the most popular cow in the herd. In a herd of N (1 <= N <= 10,000) cows, you are given up to M (1 <= M <= 50,000) ordered pairs of the form (A, B) that tell you that cow A thinks that cow B is popular. Since popularity is transitive, if A thinks B is popular and B thinks C is popular, then A will also think that C is
popular, even if this is not explicitly specified by an ordered pair in the input. Your task is to compute the number of cows that are considered popular by every other cow.
Input
-
Line 1: Two space-separated integers, N and M
-
Lines 2…1+M: Two space-separated numbers A and B, meaning that A thinks B is popular.
Output -
Line 1: A single integer that is the number of cows who are considered popular by every other cow.
Sample Input
3 3
1 2
2 1
2 3
Sample Output
1
Hint
Cow 3 is the only cow of high popularity.
出度为0的连通分量超过1时则答案为0,否则答案为出度为零的连通分量中的牛数量
#include<stdio.h>
#include<vector>
#define N 10005
using namespace std;
bool in[N];
int s[N],dfn[N],low[N],degree[N],f[N];
int ans=0,top=0,num=0;
vector<int> g[N];
void tarjan(int u)
{
int v;
s[++top]=u; //堆栈
in[u]=true; //记录是否入栈
dfn[u]=low[u]=++num; //dfn dfs序,low 到达的点中dfn最小的值
for(int i=0;i<g[u].size();i++)
{
v=g[u][i];
if(!dfn[v])
{
tarjan(v);
if(low[v]<low[u])
low[u]=low[v];
}
else if(in[v] && dfn[v]<low[u])
low[u]=dfn[v];
}
if(dfn[u]==low[u])
{
ans++; //强联通量数目
do
{
v=s[top];s[top]=0;top--; //出栈
f[v]=ans; //缩点
in[v]=false;
}while(v!=u);
}
}
int main()
{
int m,n;
scanf("%d%d",&n,&m);
int u,v;
for(int i=0;i<m;i++)
{
scanf("%d%d",&u,&v);
g[u].push_back(v);
}
for(int i=1;i<=n;i++)
{
if(!dfn[i])
{
tarjan(i);
}
}
for(int i=1; i<=n; i++)
{
for(int j=0;j<g[i].size();j++)
{
int v=g[i][j];
if(f[i]!=f[v])
degree[f[i]]++;
}
}
int sum=0,temp,cnt=0;
for(int i=1;i<=ans; i++)
{
if(!degree[i])
sum++,temp=i;
}
if(sum==1)
{
for(int i=1;i<=n;i++)
if(f[i]==temp)
cnt++;
printf("%d\n",cnt);
}
else
printf("0\n");
}