POJ2186

来源:互联网 发布:淘宝代购店铺推荐 编辑:程序博客网 时间:2024/04/28 09:12

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


题目大意是用tarjan算法求出强连通分量后进行缩点,找出入度为0的点(强连通分量)输出其大小即可。特别注意如果入度为0的强连通分量超过一个则答案为0,因为这样不存在有奶牛被其他所有奶牛青睐的情况。

上几张图便于理解


ac代码:


#include<iostream>#include<cstdio>#include<cstring>#include<stack>#include<vector>#define maxn 10100using namespace std;int low[maxn],pre[maxn],sccno[maxn],out_scc[maxn],dfs_clock,scc_cnt,n,m,cnt;stack<int>S;vector<int>G[maxn];vector<int>scc[maxn];void dfs(int u){    low[u]=pre[u]=++dfs_clock;    S.push(u);    for(int i=0;i<G[u].size();i++)    {        int v=G[u][i];        if(!pre[v])        {            dfs(v);            low[u]=min(low[u],low[v]);        }        else if(!sccno[v])low[u]=min(low[u],low[v]);    }    if(low[u]==pre[u])    {        scc_cnt++;        for(;;)        {            int x=S.top();            S.pop();            sccno[x]=scc_cnt;            scc[scc_cnt].push_back(x);            if(x==u)break;        }    }}void find_scc(int n){    dfs_clock = scc_cnt = 0;    memset(sccno,0,sizeof(sccno));    memset(pre,0,sizeof(pre));    memset(out_scc,0,sizeof(out_scc));    for(int i=1;i<=n;i++)scc[i].clear();    for(int i=1;i<=n;i++)    {        if(!pre[i])dfs(i);    }}int main(){    while(~scanf("%d%d",&n,&m))    {        int ans=0;        cnt=0;        for(int i=0;i<=n;i++)G[i].clear();        for(int i=1;i<=m;i++)        {            int x,y;            scanf("%d %d",&x,&y);            G[x].push_back(y);        }        find_scc(n);        for(int i=1;i<=n;i++)//求强连通分量的出度 {for(int j=0;j<G[i].size();j++){int k=sccno[i];int w=sccno[G[i][j]];if(k!=w)out_scc[sccno[i]]++;}}        for(int i=1;i<=scc_cnt;i++)        {                                if(out_scc[i]==0){  cnt++;  ans+=scc[i].size();}            }        if(cnt==1)cout<<ans<<endl;        else cout<<"0"<<endl;    }    return 0;}


1 0
原创粉丝点击