POJ 2186 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

Hint

Cow 3 is the only cow of high popularity. 

Source

 

大意:有N头牛 每一头牛都梦想着成为popular cow,(但这是不可能滴) 有m组仰慕的关系,仰慕有传递性 比如说A觉得B是popular and B thinks C is popular, then A thinks C is popalur also;

现在问有多少头牛是会被其他牛都仰慕。

思路:仰慕关系具有传递性,那么可以关系成环。可以用tarjan求缩点,然后看看有多少个环,只有一个环时成立,有多个环就不可能被所有牛仰慕,

#include<stack> 
#include<cstdio>
#include<iostream>
#define MAXN 10001
#define MAXM 50001
using namespace std;
struct node {
    int to;
    int next;
};
node e[MAXM+10];
int dfn[MAXN],low[MAXN],tot,head[MAXM+10];
int n,m,sum;
int out[MAXN],f[MAXN];
bool vis[MAXN];
stack<int> s;
inline void read(int&x) {
    x=0;int f=1;char c=getchar();
    while(c>'9'||c<'0') {if(c=='-') f=-1;c=getchar();}
    while(c>='0'&&c<='9') {x=(x<<1)+(x<<3)+c-48;c=getchar();}
    x=x*f;
}
inline void add(int x,int y) {
    e[++tot].to=y;
    e[tot].next=head[x];
    head[x]=tot;
}
inline void tarjan(int u) {
    dfn[u]=low[u]=++tot;
    vis[u]=true;
    s.push(u);
    for(int i=head[u];i;i=e[i].next) {
        int v=e[i].to;
        if(!dfn[v]) {
            tarjan(v);
            low[u]=min(low[u],low[v]);
        }
        else if(vis[v]) low[u]=min(low[u],dfn[v]);
    }
    if(dfn[u]==low[u]) {
        ++sum;
        int t;
        do {
            t=s.top();
            s.pop();
            vis[t]=false;
            f[t]=sum;
        }while(u!=t);
    }
}
int main() {
    int x,y;
    read(n);read(m);
    for(int i=1;i<=m;i++) {
        read(x);read(y);
        add(x,y);
    }
    tot=0;
    for(int i=1;i<=n;i++) 
      if(!dfn[i])
        tarjan(i);
    for(int i=1;i<=n;i++)
      for(int j=head[i];j;j=e[j].next) {
          int v=e[j].to;
          if(f[i]!=f[v]) {
              out[f[i]]++;
          }
      }
    int ouy=0,k;
    for(int i=1;i<=sum;i++)
      if(!out[i]) {
          ouy++;
          k=i;
      }
    if(ouy>1) printf("0\n");
    else {
        int ans=0;
        for(int i=1;i<=n;i++)
          if(f[i]==k) ans++;
        printf("%d\n",ans);
    }
    return 0;
}
View Code

 

posted @ 2017-02-07 09:12  拿叉插猹哈  阅读(171)  评论(0编辑  收藏  举报