Popular Cows

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
题意:n头牛,每头牛的心目中都有自己最欢迎的牛,欢迎可传递,如果a认为b最受欢迎,b认为c最受欢迎,那么a认为c也受欢迎。统计能出自己外能让其它所有的牛认为受欢迎的牛的数量
题解:统计所有点到一个点都可达的数量。有向无环图中所有的点至某个点可达,那么这个点的出度必为0也是唯一的出度为0的点.用tarjan算法缩点,统计缩点后的图中出度为0的数量,如果数量>1,那么不存在
否则输出该点的强连通分量点的个数。
#include<stdio.h>
#include<iostream>
#include<stack>
#include<vector>
#include<string.h>
using namespace std;
int visit[10001];
int dfn[10001],low[10001],head[10001],n,m,ret,ans,ti;
int flag[10001];
stack<int> st;
vector<int> v[10001];
int du[10001][2];
struct lmx{
 int u;
 int v;
 int next;
};
lmx a[50001];
void add(int u,int v)
{
 a[ret].u=u;
 a[ret].v=v;
 a[ret].next=head[u];
 head[u]=ret++;
}
void tarjan(int s)
{
 dfn[s]=low[s]=++ti;
 st.push(s);
 visit[s]=1;
 int k;
 for(int i=head[s];i!=-1;i=a[i].next)
 {
  int k=a[i].v;
  if(!dfn[k])
  {
   tarjan(k);
   if(low[s]>low[k]) low[s]=low[k];
  }
  else if(visit[k]&&low[s]>dfn[k]) low[s]=dfn[k];
 }
 if(dfn[s]==low[s])
 {
  ans++;
  do{
   k=st.top();
   st.pop();
   visit[k]=0;
   flag[k]=ans;
   v[ans].push_back(k);
  }while(s!=k);
 }
}
int cnt()
{
 int i,cnt=0,pos;
 if(ans==1) return n;
 memset(du,0,sizeof(du));
 for(i=0;i<m;i++)
 {
    int u=flag[a[i].u],v=flag[a[i].v];
    if(u==v) continue;
       du[u][0]++;
    du[v][1]++;
 }
 for(i=1;i<=ans;i++)
 {
  if(du[i][0]==0) {cnt++;pos=i;}
 }
 if(cnt>1) return 0;
 return v[pos].size();
}
int main()
{
 int i;
    while(scanf("%d %d",&n,&m)!=EOF)
 {
  memset(visit,0,sizeof(visit));
  memset(dfn,0,sizeof(dfn));
  memset(head,-1,sizeof(head));
  ans=ti=ret=0;
        for(i=0;i<m;i++)
  {
   int a,b;
   scanf("%d %d",&a,&b);
   add(a,b);
  }
  for(i=1;i<=n;i++) v[i].clear();
  for(i=1;i<=n;i++)
  {
   if(!dfn[i]) tarjan(i);
  }
  printf("%d\n",cnt());
 }
 return 0;
}
posted @ 2013-10-11 11:15  forevermemory  阅读(285)  评论(0编辑  收藏  举报