`
阿尔萨斯
  • 浏览: 4175391 次
社区版块
存档分类
最新评论

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

 
阅读更多

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

http://poj.org/problem?id=2186

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

分析:

首先我们把图的各个强连通分量算出来,对于分量A,如果A中的点a是那个图中所有点都可以到达的点,那么A中的其他所有点也都符合要求.

所以我们只需要把每个分量缩成一点,得到一个DAG有向无环图.然后看该DAG中的哪个点是所有其他点都可以到达的即可.那么该点代表的分量中的节点数就是所求答案.

如果DAG中出度为0的点仅有一个,那个出度为0的点代表的分量就是我们所找的分量.否则输出0.(这个结论需要自己仔细验证体会)

可不可能DAG中有两个点(分量)是满足要求的?(即分量中的所有点都是其他点可到达的)不可能,因为这两个分量如果互相可达,就会合并成一个分量.

会不会出现就算出度为0的点只有一个,但是DAG中的其他点到不了该出度为0的点,那么也应该输出0呢?如果DAG其他的点到不了出度为0的点,那么其他点必然还存在一个出度为0的点.矛盾.

AC代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<stack>
using namespace std;
const int maxn=10000+10;
int n,m;
vector<int> G[maxn];
stack<int> S;
int dfs_clock,scc_cnt;
int pre[maxn],sccno[maxn],low[maxn];
int num[maxn];//num[i]=x表第i个分量中有x个节点
bool out0[maxn];//标记新DAG图出度为0的节点
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++;
        while(true)
        {
            int x=S.top(); S.pop();
            sccno[x]=scc_cnt;
            num[scc_cnt]++;
            if(x==u) break;
        }
    }
}
void find_scc(int n)
{
    scc_cnt=dfs_clock=0;
    memset(pre,0,sizeof(pre));
    memset(sccno,0,sizeof(sccno));
    memset(num,0,sizeof(num));
    for(int i=1;i<=n;i++)
        if(!pre[i]) dfs(i);
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++) G[i].clear();
    while(m--)
    {
        int u,v;
        scanf("%d%d",&u,&v);
        G[u].push_back(v);
    }
    find_scc(n);
    for(int i=1;i<=scc_cnt;i++) out0[i]=true;
    for(int u=1;u<=n;u++)
    for(int i=0;i<G[u].size();i++)
    {
        int v=G[u][i];
        int x=sccno[u], y=sccno[v];
        if(x!=y) out0[x]=false;
    }
    int a=0,pos;
    for(int i=1;i<=scc_cnt;i++)
        if(out0[i]) a++,pos=i;
    if(a==1) printf("%d\n",num[pos]);
    else printf("0\n");
    return 0;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics