hdu 1269 迷宫城堡 - 有向图的连通分量

迷宫城堡

Problem Description
为了训练小希的方向感,Gardon建立了一座大城堡,里面有N个房间(N<=10000)和M条通道(M<=100000),每个通道都是单向的,就是说若称某通道连通了A房间和B房间,只说明可以通过这个通道由A房间到达B房间,但并不说明通过它可以由B房间到达A房间。Gardon需要请你写个程序确认一下是否任意两个房间都是相互连通的,即:对于任意的i和j,至少存在一条路径可以从房间i到房间j,也存在一条路径可以从房间j到房间i。
 

Input
输入包含多组数据,输入的第一行有两个数:N和M,接下来的M行每行有两个数a和b,表示了一条通道可以从A房间来到B房间。文件最后以两个0结束。
 

Output
对于输入的每组数据,如果任意两个房间都是相互连接的,输出"Yes",否则输出"No"。
 

Sample Input
  
  
3 3 1 2 2 3 3 1 3 3 1 2 2 3 3 2 0 0
 

Sample Output
  
  
Yes No
 


解题思路

有向图连通分量模板题



代码

#include <iostream>
#include <cstdio>
#include <map>
#include <cmath>
#include <string.h>
#include <algorithm>
#include <set>
#include <sstream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;

const int maxn = 10000+10;
const int INF = 0x3f3f3f3f;


vector<int> G[maxn];
int pre[maxn];///第一次进入dfs时的层数
int lowlink[maxn];///能追溯到的dfs层数最小(最先被发现)的根祖先的 pre 值
int sccno[maxn];///当前点属于第几个连通分量
int dfsLock;///dfs层数
int sccCnt;///连通分量个数

stack<int> s;

int n,m;


void dfs(int u){
    ///一开始并不知道这个点的根祖是谁,也不知道跟祖先最先在第几层进入dfs
    pre[u] = lowlink[u] = ++dfsLock;

    s.push(u);
    ///遍历这个点能到达的点
    for(int i = 0;i<G[u].size(); ++i){
        int v = G[u][i];
        if(!pre[v]){///这个点没有进入过dfs
            dfs(v);
            ///是否通过v点找到了u点的祖先,如果是,更新u点的最小层数
            lowlink[u] = min(lowlink[u],lowlink[v]);
        }
        ///如果这个点已经进入过dfs了,但是还没确定是属于哪个连通分支的点
        ///这个点可能是u点的祖先
        else if(!sccno[v]){
            lowlink[u] = min(lowlink[u],pre[v]);///*****这里书上写的是pre 个人觉得写lowlink是一样的,不知道对不对****
        }
    }

    ///如果他下面的点都没有改变他的最小值,说明他是一个根祖先,也就是一个连通分支的入口
    if(lowlink[u] == pre[u]){
        sccCnt++;

        while(1){
            int x = s.top(); s.pop();
            sccno[x] = sccCnt;
            if(x == u) break;
        }
    }

}


int main()
{
    while(scanf("%d%d",&n,&m)!=EOF){
        if(m==0 && n==0) break;

        ///初始化
        for(int i =0; i<maxn; ++i) G[i].clear();
        while(!s.empty()) s.pop();
        memset(pre,0,sizeof(pre));
        memset(lowlink,0,sizeof(lowlink));
        memset(sccno,0,sizeof(sccno));
        dfsLock = sccCnt = 0;

        int u,v;
        for(int i = 0;i<m;++i){
            scanf("%d%d",&u,&v);
            G[u-1].push_back(v-1);
        }
        for(int i = 0; i<n; ++i){
            if(!pre[i]) dfs(i);
        }
        if(sccCnt==1) printf("Yes\n");
        else printf("No\n");
    }


    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值