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

HDU 1269 迷宫城堡(强连通分量)

 
阅读更多

HDU 1269 迷宫城堡(强连通图判定)

http://acm.hdu.edu.cn/showproblem.php?pid=1269

题意:给你一个有向图,问你该图是否是一个强连通的图?

分析:

直接tarjan强连通算法求出scc_cnt(强连通分量的数目),看看scc_cnt是否为1即可.

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],low[maxn],sccno[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++;
        while(true)
        {
            int x=S.top(); S.pop();
            sccno[x]=scc_cnt;
            if(x==u) break;
        }
    }
}
void find_scc(int n)
{
    dfs_clock=scc_cnt=0;
    memset(pre,0,sizeof(pre));
    memset(sccno,0,sizeof(sccno));
    for(int i=1;i<=n;i++)
        if(!pre[i]) dfs(i);
}
int main()
{
    while(scanf("%d%d",&n,&m)==2)
    {
        if(n==0 && m==0) break;
        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);
        printf("%s\n",scc_cnt==1?"Yes":"No");
    }
    return 0;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics