# poj 2186 Popular Cows（强连通分量模板题，tarjan）

Popular Cows
 Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 30374 Accepted: 12323

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

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define N 10050
#define M 50050
struct Edge
{
int v,next;
} edge[M];
int dfn[N];
int low[N];
int s[N],top;
int instack[N];
int num;
int index;
int belong[N];
int out[N];
void init()
{
cnt=0;
num=1;
index = 0;
top=0;
memset(dfn, -1, sizeof(dfn));
memset(low, -1, sizeof(low));
memset(instack, 0, sizeof(instack));
memset(belong, 0, sizeof(belong));
memset(out, 0, sizeof(out));
}
{
edge[cnt].v=v;
}
void tarjan(int u)
{
int v, i;
dfn[u] = low[u] = num++;
instack[u] = 1;
s[++top] = u;
for(i = head[u]; i != -1; i = edge[i].next)
{
v = edge[i].v;
if(dfn[v] == -1)
{
tarjan(v);
low[u] = min(low[u], low[v]);
}
else if(instack[v])
{
low[u] = min(low[u], dfn[v]);
}
}

if(low[u] == dfn[u])
{
index++;
do
{
v = s[top--];
instack[v] = 0;
belong[v] = index;
}
while(top != 0 && v != u);
}
}
int main()
{
int n,m;
int u,v;
while(~scanf("%d %d",&n,&m))
{
init();
for(int i=1; i<=m; i++)
{
scanf("%d %d",&u,&v);
}
for(int i=1; i<=n; i++)
if(dfn[i]==-1)
tarjan(i);
for(int j=1; j<=n; j++)
if(belong[j]!=belong[edge[i].v])
out[belong[j]]++;
int ans,tot=0;
for(int i=1; i<=index; i++)
if(!out[i])
{
tot++;
ans=i;
}
for(int i=1;i<=n;i++)
if(!belong[i])
tot=0;
if(tot==1)
{
int q=0;
for(int i=1; i<=n; i++)
if(belong[i]==ans)
q++;
printf("%d\n",q);
}
else printf("0\n");
}
return 0;
}