首页 > 代码库 > POJ2186 Popular Cows [tarjan 缩点]

POJ2186 Popular Cows [tarjan 缩点]

Popular Cows
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 31241 Accepted: 12691

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 31 22 12 3

Sample Output

1

Hint

Cow 3 is the only cow of high popularity. 

Source

USACO 2003 Fall

题意:

每头奶牛都梦想成为牛棚里的明星。被所有奶牛喜欢的奶牛就是一头明星奶牛。所有奶

牛都是自恋狂,每头奶牛总是喜欢自己的。奶牛之间的“喜欢”是可以传递的——如果A喜

欢B,B喜欢C,那么A也喜欢C。牛栏里共有N 头奶牛,给定一些奶牛之间的爱慕关系,请你

算出有多少头奶牛可以当明星。


 

第三道了

出度为0的scc只有一个答案就是它的size

否则无解

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>using namespace std;const int N=1e4+5,M=5e4+5;typedef long long ll;inline int read(){    char c=getchar();int x=0,f=1;    while(c<0||c>9){if(c==-)f=-1;c=getchar();}    while(c>=0&&c<=9){x=x*10+c-0;c=getchar();}    return x*f;}int n,m,u,v;struct edge{    int v,ne;}e[M];int h[N],cnt=0;inline void ins(int u,int v){    cnt++;    e[cnt].v=v;e[cnt].ne=h[u];h[u]=cnt;}int dfn[N],belong[N],low[N],dfc,scc,st[N],top;int size[N];void dfs(int u){    dfn[u]=low[u]=++dfc;    st[++top]=u;    for(int i=h[u];i;i=e[i].ne){        int v=e[i].v;        if(!dfn[v]){            dfs(v);            low[u]=min(low[u],low[v]);        }else if(!belong[v])            low[u]=min(low[u],dfn[v]);    }    if(low[u]==dfn[u]){        scc++;        while(true){            int x=st[top--];            belong[x]=scc;            size[scc]++;            if(x==u) break;        }    }}int outd[N],ind[N],ans;void point(){    for(int u=1;u<=n;u++)        for(int i=h[u];i;i=e[i].ne){            int v=e[i].v;            if(belong[u]!=belong[v]) outd[belong[u]]++,ind[belong[v]]++;        }}int main(){    n=read();m=read();    for(int i=1;i<=m;i++){u=read();v=read();ins(u,v);}    for(int i=1;i<=n;i++) if(!dfn[i]) dfs(i);    point();     for(int i=1;i<=scc;i++){        if(outd[i]==0){            if(ans){ans=0;break;}            else ans=size[i];         }    }    printf("%d",ans);}

 

POJ2186 Popular Cows [tarjan 缩点]