POJ 2186 Popular Cows(强连通分量+缩点)

题目链接:http://poj.org/problem?id=2186

借鉴了一位大佬的思路:https://blog.csdn.net/u013480600/article/details/32107733

题意:给你一个有向图,现在问你图中有多少个顶点满足下面要求:任何其他的点都有路可以走到该顶点. 输出满足要求顶点的数目.

分析:
先我们把图的各个强连通分量算出来,对于分量A,如果A中的点a是那个图中所有点都可以到达的点,那么A中的其他所有点也都符合要求.
所以我们只需要把每个分量缩成一点,得到一个DAG有向无环图.然后看该DAG中的哪个点是所有其他点都可以到达的即可.那么该点代表的分量中的节点数就是所求答案.

如果DAG中出度为0的点仅有一个,那个出度为0的点代表的分量就是我们所找的分量.否则输出0.(这个结论需要自己仔细验证体会)
可不可能DAG中有两个点(分量)是满足要求的? (即分量中的所有点都是其他点可到达的)不可能,因为这两个分量如果互相可达,就会合并成一个分量.会不会出现就算出度为0的点只有一个,但是DAG中的其他点到不了该出度为0的点,那么也应该输出0呢?如果DAG其他的点到不了出度为0的点,那么其他点必然还存在一个出度为0的点.矛盾.

代码如下:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <stdlib.h>
#include <vector>
#include <map>
#include <stack>
#include <queue>
using namespace std;

const int maxn =10000+10;
int n,m;
int pre[maxn],low[maxn],sccno[maxn],dfs_clock,scc_cnt,w[maxn],outdeg[maxn];
stack<int>S;
vector<int>G[maxn];



void dfs(int u)
{
    pre[u] = low[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],pre[v]);
        }
    }
    if(low[u]==pre[u])
    {

        scc_cnt++;
        int cnt =0;
        for(; ;)
        {
            cnt++;
            int x = S.top();
            S.pop();
            sccno[x] = scc_cnt;
            if(x==u)
                break;
        }
        w[scc_cnt]=cnt;
    }
}


void find_scc()
{
    dfs_clock = scc_cnt =0;
    memset(sccno,0,sizeof(sccno));
    memset(outdeg,0,sizeof(outdeg));//出度
    memset(w,0,sizeof(w));//每一个缩点有多少个点
    memset(pre,0,sizeof(pre));
    for(int i=0; i<n; i++)
        if(!pre[i])
            dfs(i);
}

void build()
{

    for(int u=0; u<n; u++)
    {
        for(int i=0; i<G[u].size(); i++)
        {
            int v=G[u][i];
            if(sccno[u]!=sccno[v])
            {

                outdeg[sccno[u]]++;
            }
        }
    }
}



int main()
{

    while(scanf("%d %d",&n,&m)!=EOF)
    {
        int ans=0;
        for(int i=0; i<n; i++)
            G[i].clear();

        int u,v;
        for(int i=0; i<m; i++)
        {
            scanf("%d %d",&u,&v);
            u--,v--;
            G[u].push_back(v);
        }

        find_scc();//缩点

        if(scc_cnt==1)
        {
            printf("%d\n",n);
            continue;
        }

        build();//建图


        int sum=0;
        for(int i=1; i<=scc_cnt; i++)
        {
            if(outdeg[i]==0)
            {
                sum++;
                ans+=w[i];
            }
        }

        if(sum!=1)
        {
            ans=0;
        }

        printf("%d\n",ans);

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36300700/article/details/81262506
今日推荐