http://poj.org/problem?id=2186
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.
题目大意:给出牛与牛之间的关系:
(
x
,
y
)
(x,y)
(x,y)代表第
x
x
x只牛认为第
y
y
y只牛是受欢迎的,这个关系是可以传递的。问被其他所有牛认为是受欢迎的牛的个数。
思路:
(
x
,
y
)
(x,y)
(x,y)代表从
x
x
x到
y
y
y的一条有向边,显然图的每个强连通分量中的牛在这个分量内是满足题意的,我们把强连通分量缩点,就得到一个
D
A
G
DAG
DAG,问题就是在这个
D
A
G
DAG
DAG中找到一个点,这个点满足从任意点出发均可到达该点,答案就是这个点对应的强连通分量的点的个数。设
p
p
p为一个
D
A
G
DAG
DAG中出度等于
0
0
0的点的个数,显然当
p
>
1
p>1
p>1时,答案是0。而当
p
=
1
p=1
p=1时,根据
D
A
G
DAG
DAG的性质,这个出度为
0
0
0的点,是其他所有点都可以到达的,故答案就是该点对应的强连通分量的点的数目。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
const int maxn=1e4+5;
const int maxm=5e4+5;
struct edge
{
int to,nxt;
}Edge[maxm];
int head[maxn],dfn[maxn],low[maxn],Stack[maxn],ins[maxn],id[maxn];
int outd[maxn],siz[maxn];
int ans;
int n,m,tot,num,top,cnt;
void addedge(int x,int y)
{
Edge[++tot].to=y,Edge[tot].nxt=head[x],head[x]=tot;
}
void tarjan(int x)
{
dfn[x]=low[x]=++num;
Stack[++top]=x,ins[x]=1;
int y;
for(int i=head[x];i;i=Edge[i].nxt)
{
y=Edge[i].to;
if(!dfn[y])
{
tarjan(y);
low[x]=min(low[x],low[y]);
}
else if(ins[y])
low[x]=min(low[x],dfn[y]);
}
if(dfn[x]==low[x])
{
++cnt;
do
{
y=Stack[top--],ins[y]=0;
id[y]=cnt,++siz[cnt];
}while(x!=y);
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
num=top=cnt=tot=0;
memset(dfn,0,sizeof(dfn));
memset(head,0,sizeof(head));
memset(siz,0,sizeof(siz));
int x,y;
for(int i=0;i<m;i++)
{
scanf("%d%d",&x,&y);
addedge(x,y);
}
for(int i=1;i<=n;i++)
if(!dfn[i])
tarjan(i);
for(int i=1;i<=n;i++)
{
for(int j=head[i];j;j=Edge[j].nxt)
{
y=Edge[j].to;
if(id[i]!=id[y])
outd[id[i]]++;
}
}
int flag=0;
for(int i=1;i<=cnt;i++)
{
if(outd[i]==0)
++flag,ans=siz[i];
}
printf("%d\n",flag>1?0:ans);
}
return 0;
}