传送门:POJ 2186
Problem 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.
题意:
告诉你有n头牛,m个崇拜关系,并且崇拜具有传递性,如果a崇拜b,b崇拜c,则a崇拜c,求最后有几头牛被所有牛崇拜。
题解:
很显然,如果一头牛满足条件,那么和它在一个强连通分量里的其他牛也会满足条件,所以我们将图进行缩点,然后就简单了。(缩点后变成一个有向无环图)
只要判断缩点后各点的出度就行了。缩点后是图比然有一个即以上的点出度为0,如果有两个点出度为0,那么这两个点必然是没有崇拜关系的,无要求不符,所以答案为0。如果有1个点出度为0,那么这个点就是被全体牛崇拜的,这个点可能是一个强联通分量缩成的超级点,所以应该输出整个强联通分量中点的个数(因为没考虑到这个错了两发Orz)。
AC代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<stack>
#include<cstdio>
#include<cmath>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const int N=110000;
int n,m;
struct edge
{
int to,next;
}e[N];
int num[N];//记录每个强连通分量里有多少个点
int dfn[N],low[N];
int vis[N];
int belong[N],head[N];
int bcnt,k,idx;
int in[N],out[N];
stack<int> s;
void add(int u,int v)
{
e[k].to=v;
e[k].next=head[u];
head[u]=k++;
}
void tarjan(int u)
{
int v;
dfn[u]=low[u]=++idx;
s.push(u);
vis[u]=1;
for(int i=head[u];i!=-1;i=e[i].next)
{
v=e[i].to;
if(!dfn[v])
{
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(vis[v])
{
low[u]=min(low[u],dfn[v]);
}
}
if(dfn[u]==low[u])
{
bcnt++;
do
{
v=s.top();
s.pop();
vis[v]=0;
belong[v]=bcnt;
num[bcnt]++;
}while(u!=v);
}
}
int main()
{
int a,b;
while(scanf("%d%d",&n,&m)!=EOF)
{
while(!s.empty()) s.pop();
memset(head,-1,sizeof(head));
memset(in,0,sizeof(in));
memset(out,0,sizeof(out));
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(belong,0,sizeof(belong));
k=1,idx=0,bcnt=0;
for(int i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
add(a,b);
}
for(int i=1;i<=n;i++)
{
if(!dfn[i])
{
tarjan(i);
}
}
int v;
for(int u=1;u<=n;u++)
{
for(int i=head[u];i!=-1;i=e[i].next)
{
v=e[i].to;
if(belong[v]!=belong[u])
{
in[belong[v]]=out[belong[u]]=1;
}
}
}
int ansout=0,tmp=0;
for(int i=1;i<=bcnt;i++)
{
if(!out[i])
{
tmp++;
ansout=num[i];
}
}
if(tmp==0)
{
printf("0\n");
}
else
{
if(tmp>1) printf("0\n");
else printf("%d\n",ansout);
}
}
return 0;
}