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.
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.
* 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.
Source
题目大意:
n头奶牛,给出若干个欢迎关系a b,表示a欢迎b,欢迎关系是单向的,但是是可以传递的。另外每个奶牛都是欢迎他自己的。求出被所有的奶牛欢迎的奶牛的数目
思路:
先跑一遍taijian算法。那么出度为0的强连通分量代表的就是受其他奶牛欢迎的,但是如果出度为0的强连通分量的个数大于1.那么则无解。因为将至少有两个分量里的奶牛互相不喜欢。所以我们的算法就是如果出度为0的强连通分量的个数是1.那么我们算出这里面点的个数就是最后的答案。
源代码:
#include <stdio.h>
#include <cstring>
#include <stack>
using namespace std;
struct edge
{
int x,y,next;
};
int n,t,maxE=0;
int comp[10005],dfn[10005],low[10005],oud[10005],ls[10005];
edge e[100005];
stack<int>s;
int min(int x,int y)
{
return x<y?x:y;
}
void tarjan(int x)
{
int y;
dfn[x]=++t;
low[x]=t;
s.push(x);
for (int i=ls[x];i;i=e[i].next)
{
y=e[i].y;
if (!dfn[y])
tarjan(y),low[x]=min(low[x],low[y]);
else
low[x]=min(low[x],dfn[y]);
}
if (dfn[x]==low[x])
{
comp[0]++;
do
{
y=s.top();
s.pop();
comp[y]=comp[0];
}while(x!=y);
}
}
void print()
{
memset(oud,0,sizeof(oud));
int x=0,y=0,ans=0;
for (int i=1;i<=maxE;i++)
if (comp[e[i].x]!=comp[e[i].y])
oud[comp[e[i].x]]++;
for (int i=1;i<=comp[0];i++)
if (!oud[i])
y++,x=i;
if (y==1)
for (int i=1;i<=n;i++)
if (comp[i]==x)
ans++;
printf("%d\n",ans);
}
int main()
{
scanf("%d%d",&n,&maxE);
for (int i=1;i<=maxE;i++)
{
scanf("%d%d",&e[i].x,&e[i].y);
e[i].next=ls[e[i].x];
ls[e[i].x]=i;
}
for (int i=1;i<=n;i++)
if (!dfn[i])
tarjan(i);
print();
return 0;
}