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.
题意:
给出仰慕关系, 求有几个奶牛被除了自己的所有奶牛仰慕。
看着题解才勉强看懂。 。
先对给出的关系运用targan算法+缩点将强连通分量进行缩点。 。
如果缩点为1个, 则说明这n个奶牛相互崇拜。 。。
然后求他们的出度。
如果有大于1个的点出度为0, 说明所有的奶牛都不符合条件。 。为神魔呢, 因为出度大于1的话, 说明至少有一只奶牛谁也不崇拜, 所以不满足条件。
如果只有一个点出度为1, 则说明这个缩点的所有点都符合条件, 只要求出此缩点有多少个点即可。 。
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
const int maxn=10005;
vector <int>ve[maxn];
int n,m;
int dfn[maxn],low[maxn],ccnc[maxn],on[maxn];
int tot,ccnum;
stack<int>s;
void init ()
{
ccnum=tot=0;
memset (dfn,0,sizeof(dfn));
memset (low,0,sizeof(low));
memset (ccnc,0,sizeof(ccnc));
memset (on,0,sizeof(on));
for (int i=0;i<=n;i++)
ve[i].clear();
while (!s.empty())
s.pop();
}
void targan (int x)
{
dfn[x]=low[x]=++tot;
s.push(x);
for (int i=0;i<ve[x].size();i++)
{
int v=ve[x][i];
if(!dfn[v])
{
targan(v);
low[x]=min(low[x],low[v]);
}
else if(!ccnc[v])
low[x]=min(low[x],dfn[v]);
}
if(low[x]==dfn[x])
{
ccnum++;
while (1)
{
int now=s.top();
s.pop();
ccnc[now]=ccnum;
if(now==x)
break;
}
}
}
void finds ()
{
if(ccnum==1)
{
printf("%d\n",n);
return;
}
for (int i=1;i<=n;i++)
{
for (int j=0;j<ve[i].size();j++)
{
int v=ve[i][j];
if(ccnc[i]!=ccnc[v])
{
on[ccnc[i]]++;
}
}
}
int num=0,loc,ans=0;
for (int i=1;i<=ccnum;i++)
if(!on[i])
{
num++;
loc=i;
}
if(num>1)
{
printf("0\n");
return;
}
for (int i=1;i<=n;i++)
if(ccnc[i]==loc)
ans++;
printf("%d\n",ans);
}
int main()
{
while (scanf("%d%d",&n,&m)!=EOF)
{
init();
while (m--)
{
int x,y;
scanf("%d%d",&x,&y);
ve[x].push_back(y);
}
for (int i=1;i<=n;i++)
if(!dfn[i])
targan(i);
finds();
}
return 0;
}