Popular Cows
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 24320 | Accepted: 9979 |
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
ac代码
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
#define INF 0xfffffff
#define max(a,b) (a>b?a:b)
#define min(a,b) (b>a?a:b)
using namespace std;
int dfn[101000],low[100010],ins[100100],belong[100010],dig[100010],stack[100010],head[100010];
int cnt,top,taj,time;
int n,m;
struct s
{
int u,v,next;
}edge[200100];
void add(int u,int v)
{
edge[cnt].u=u;
edge[cnt].v=v;
edge[cnt].next=head[u];
head[u]=cnt++;
}
void init()
{
memset(head,-1,sizeof(head));
memset(belong,-1,sizeof(belong));
memset(low,-1,sizeof(low));
memset(dfn,-1,sizeof(dfn));
memset(ins,0,sizeof(ins));
top=cnt=taj=time=0;
}
void tarjan(int u)
{
stack[top++]=u;
ins[u]=1;
low[u]=dfn[u]=time++;
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].v;
if(dfn[v]==-1)
{
tarjan(v);
low[u]=min(low[u],low[v]);
}
else
if(ins[v])
low[u]=min(low[u],dfn[v]);
}
if(dfn[u]==low[u])
{
int now;
taj++;
do
{
now=stack[--top];
belong[now]=taj;
ins[now]=0;
}while(now!=u);
}
}
int main()
{
//int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
int i,sum=0,ans=0;
init();
for(i=0;i<m;i++)
{
int a,b;
scanf("%d%d",&a,&b);
add(a,b);
}
for(i=1;i<=n;i++)
{
if(dfn[i]==-1)
tarjan(i);
}
memset(dig,0,sizeof(dig));
for(i=0;i<cnt;i++)
{
int u=edge[i].u;
int v=edge[i].v;
if(belong[u]!=belong[v])
{
dig[belong[u]]++;
}
}
int x;
for(i=1;i<=taj;i++)
{
if(dig[i]==0)
{
sum++;
x=i;
}
}
if(sum==1)
{
for(i=1;i<=n;i++)
{
if(belong[i]==x)
{
ans++;
}
}
printf("%d\n",ans);
}
else
printf("0\n");
}
}