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.
大意:一个无向图,问你有多少个点使得其他所有点均可到达这。。
一个小定理:
对于一个有向无环图来说,其中有且仅有一个点的出度为0,这个点可以由其余任何点到达。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=500000+100;
struct node
{
int v,nxt;
}edge[maxn*2+100];
int cnt=0,head[maxn*2+100];
void add_edge(int u,int v)
{
edge[cnt].v=v;
edge[cnt].nxt=head[u];
head[u]=cnt++;
}
int dfn[maxn],low[maxn],instackk[maxn],stackk[maxn],belong[maxn];
int in[maxn],out[maxn];
int index,top,block;
int n,m;
void tarjan(int u,int pre)
{
int v;
dfn[u]=low[u]=++index;
stackk[top++]=u;
instackk[u]=1;
for(int i=head[u];i!=-1;i=edge[i].nxt)
{
v=edge[i].v;
if(!dfn[v])
{
tarjan(v,u);
low[u]=min(low[u],low[v]);
}
else if(instackk[v]==1)
{
low[u]=min(low[u],dfn[v]);
}
}
if(low[u]==dfn[u])
{
block++;
do
{
v=stackk[--top];
belong[v]=block;
instackk[v]=0;
}while(u!=v);
}
}
void solve()
{
// int flag=0;
// tarjan(1,1);
for(int i=1;i<=n;i++)
{
if(!dfn[i])
{
tarjan(i,i);
// flag=1;
}
}
for(int i=1;i<=n;i++)
{
for(int j=head[i];j!=-1;j=edge[j].nxt)
{
int v=edge[j].v;
if(belong[i]!=belong[v])
{
out[belong[i]]++;
in[belong[v]]++;
}
}
}
int ans=0;
/*if(flag==1)
{
printf("0\n");
}
else*/
{
int id=-1;
/* for(int i=1;i<=n;i++)
{
printf(":%d %d\n",i,belong[i]);
}*/
for(int i=1;i<=block;i++)
{
// printf("::%d\n",out[i]);
if(out[i]==0)
{
ans++;
id=i;
//printf("%d \n",i);
}
}
//printf("%d\n",ans);
if(ans!=1)
{
printf("0\n");
}
else
{
ans=0;
for(int i=1;i<=n;i++)
{
//printf("%d %d %d\n",i,belong[i],out[belong[i]]);
if(belong[i]==id)
{
ans++;
}
}
printf("%d\n",ans);
}
}
}
int main ()
{
while(~scanf("%d%d",&n,&m))
{
memset(head,-1,sizeof(head));
cnt=0;
index=top=block=0;
memset(dfn,0,sizeof(dfn));
memset(instackk,0,sizeof(instackk));
memset(in,0,sizeof(in));
memset(out,0,sizeof(out));
while(m--)
{
int xx,yy;
scanf("%d%d",&xx,&yy);
add_edge(xx,yy);
}
solve();
}
}