Description
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.
================================这是分割线===================================
求强连通分量,统计入度为零的点,只能有一个,输出奶牛个数即可。
================================这是分割线===================================
#include<iostream>
#include<vector>
#include<cstdio>
#include<stack>
using namespace std;
stack<int>st;
vector<int>v[10001];
int n,m,tim,dcnt,dfn[10001],belong[10001],low[10001],x[50001],y[50001],ncnt[10001];
bool instack[10001],flag[10001];
void dfs(int u)
{
int tmp;
dfn[u]=low[u]=++tim;
instack[u]=1;
st.push(u);
for(int i=0;i<v[u].size();i++)
{
int j=v[u][i];
if(dfn[j]==0)
{
dfs(j);
low[u]=min(low[j],low[u]);
}
else if(instack[j])
low[u]=min(low[u],dfn[j]);
}
if(dfn[u]==low[u])
{
dcnt++;
do
{
tmp=st.top();
st.pop();
instack[tmp]=0;
belong[tmp]=dcnt;
}while(u!=tmp);
}
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
scanf("%d%d",&x[i],&y[i]);
v[x[i]].push_back(y[i]);
}
for(int i=1;i<=n;i++)
if(dfn[i]==0)
dfs(i);
for(int i=1;i<=m;i++)
if(belong[x[i]]!=belong[y[i]])
flag[belong[x[i]]]=1;
for(int i=1;i<=n;i++)
ncnt[belong[i]]++;
int times=0,ans=0;
for(int i=1;i<=dcnt;i++)
if(!flag[i])
{
ans=ncnt[i];
times++;
}
if(times==1)
printf("%d\n",ans);
else
printf("0\n");
return 0;
}