K - Popular Cows

时间:2024-01-01 11:42:21

来源poj2186

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.

tarjan要找出受其他牛都欢迎的,强通量出度为0的只能有1个,否者就没有牛都受其他牛欢迎;

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include <iomanip>
#include<cmath>
#include<float.h>
#include<string.h>
#include<algorithm>
#define sf scanf
#define pf printf
#define mm(x,b) memset((x),(b),sizeof(x))
#include<vector>
#include<queue>
#include<map>
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=a;i>=n;i--)
typedef long long ll;
const ll mod=1e9+100;
const double eps=1e-8;
using namespace std;
const double pi=acos(-1.0);
const int inf=0xfffffff;
const int N=10005;
struct Edge {
int v,next;
}edge[5*N];
int dfn[N],low[N];
int stack[N],node[N],visit[N],cnt,tot,index;
int belong[N],bcnt;
void add_edge(int x,int y)
{
edge[cnt].next=node[x];
edge[cnt].v = y;
node[x]=cnt++;
return ;
}
void tarjan(int x)//代表第几个点在处理。递归的是点。
{
dfn[x]=low[x]=++tot;// 新进点的初始化。
stack[++index]=x;//进站
visit[x]=1;//表示在栈里
for(int i=node[x];i!=-1;i=edge[i].next)
{
if(!dfn[edge[i].v]) {//如果没访问过
tarjan(edge[i].v);//往下进行延伸,开始递归
low[x]=min(low[x],low[edge[i].v]);//递归出来,比较谁是谁的儿子/父亲,就是树的对应关系,涉及到强连通分量子树最小根的事情。
}
else if(visit[edge[i].v ]){ //如果访问过,并且还在栈里。
low[x]=min(low[x],dfn[edge[i].v]);//比较谁是谁的儿子/父亲。就是链接对应关系
}
}
if(low[x]==dfn[x]) //发现是整个强连通分量子树里的最小根。
{
bcnt++;
do{
belong[stack[index]]=bcnt;
visit[stack[index]]=0;
index--; }while(x!=stack[index+1]);//出栈,并且输出。
}
return ;
}
int in[N],out[N],num[N];
void solve(int n)
{
tot=index=bcnt=0;
mm(dfn,0);
mm(low,0);
mm(belong,0);
mm(out,0);
mm(visit,0);
mm(num,0);
rep(i,1,n+1)
if(!dfn[i])
tarjan(i);
int ans1=0,ans2=0;
rep(i,1,n+1)
{
num[belong[i]]++;
for(int j=node[i];j!=-1;j=edge[j].next)
{
if(belong[i]!=belong[edge[j].v])
{
out[belong[i]]++;
}
}
}
int bits=0,ans;
rep(i,1,bcnt+1)
{
if(out[i]==0)
{
bits++;
ans=i;
}
}
if(bits>1)
{
pf("0\n");
}else
pf("%d\n",num[ans]);
}
int main()
{
int n,m;
while(~sf("%d%d",&n,&m))
{
mm(node,-1);
cnt=0;
rep(i,1,m+1)
{
int x,y;
sf("%d%d",&x,&y);
add_edge(x,y);
}
solve(n);
} return 0;
}