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条边,每条边ab表示a喜欢b,问有多少头牛被其他所有牛都喜欢
思路:缩点后找出度为0的点,如果点数大于1,那么输出0,否则出度为0的点在的强连通分量的所有点都可以
#include <cstdio>
#include<iostream>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;
#define ll long long
const int maxn=2e5;
stack<int>q;
int cnt,n,m,head[maxn],dfn[maxn],low[maxn],co[maxn],tot,id,out[maxn],a[maxn];
struct Edge
{
int to,next;
}e[maxn];
void add(int u,int v)
{
e[cnt].to=v;
e[cnt].next=head[u];
head[u]=cnt++;
}
void init()
{
memset(out,0,sizeof(out));
memset(co,0,sizeof(co));
memset(head,-1,sizeof(head));
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
while(!q.empty()) q.pop();
cnt=0;id=0,tot=0;
}
void tarjan(int u)
{
q.push(u);
dfn[u]=low[u]=++tot;
for(int i=head[u];i!=-1;i=e[i].next)
{
int v=e[i].to;
if(!dfn[v])
{
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(!co[v])
low[u]=min(low[u],dfn[v]);
}
if(low[u]==dfn[u])
{
id++;
while(q.top()!=u)
{
int x=q.top();
q.pop();
co[x]=id;
}
co[u]=id;
q.pop();
}
}
int main()
{
while(scanf("%d %d",&n,&m)!=EOF)
{
init();
for(int i=1;i<=m;i++)
{
int u,v;
scanf("%d %d",&u,&v);
add(u,v);
}
for(int i=1;i<=n;i++)
{
if(dfn[i]==0)
{
tarjan(i);
}
}
for(int u=1;u<=n;u++)
{
for(int i=head[u];i!=-1;i=e[i].next)
{
int v=e[i].to;
if(co[u]!=co[v])
{
a[co[u]]++;
}
}
}
int s=0,x=0;
for(int i=1;i<=id;i++)
{
if(a[i]==0)
{
s++;
x=i;
}
}
if(s>=2) printf("0\n");
else
{
int sum=0;
for(int i=1;i<=n;i++)
{
if(co[i]==x) sum++;
}
printf("%d\n",sum);
}
}
}