hdu 1269 迷宫城堡 强连通分量

Problem:
给一个有向图,问这个图是否两两都可互相达。
Solution:
求强连通分量,看一共有几个强连通分量,如果只有一个则两两可互相达。

#include<cstdio>
#include<iostream>
#include<sstream>
#include<cstdlib>
#include<cmath>
#include<cctype>
#include<string>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<ctime>
#include<vector>
#include<fstream>
#include<list>
using namespace std;

#define ms(s) memset(s,0,sizeof(s))
typedef unsigned long long ULL;
typedef long long LL;

const double PI = 3.141592653589;
const int INF = 0x3fffffff;

int n, m;

const int maxn = 10010;
stack<int> stk;
vector<int> G[maxn];
int dfn[maxn], low[maxn], vis[maxn];
int times, tot;//强连通分量的个数

void tarjan(int u){
    dfn[u] = low[u] = ++times;
    stk.push(u);  vis[u] = -1;
    for(int i = 0; i < G[u].size(); ++i){
        int v = G[u][i];
        if(vis[v] == 0){
            tarjan(v);
            low[u] = min(low[u], low[v]);
        }
        else{
            if(vis[v] == -1)
                low[u] = min(low[u], dfn[v]);
        }
    }
    if(dfn[u] == low[u]){//u是一个强连通分量的根
        tot++;
        while(!stk.empty()){
            int v = stk.top();  stk.pop();
            vis[v] = 1;
            if(v == u)
                break;
        }
    }
}
void solve(int n){
    for(int i = 1; i <= n; ++i){
        if(vis[i] == 0)
            tarjan(i);
    }
}


int main(){
//    freopen("E:\\input.txt","r",stdin);
//    freopen("/home/really/Document/output","w",stdout);
//    ios::sync_with_stdio(false);

    int a,b;
    while(scanf("%d%d",&n,&m) && (n||m)){
        times = tot = 0;
        ms(vis);
        while(!stk.empty())
            stk.pop();
        for(int i = 1; i <= n; ++i)
            G[i].clear();
        for(int i = 0; i < m; ++i){
            scanf("%d%d",&a,&b);
            G[a].push_back(b);
        }
        solve(n);
        if(tot <= 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、付费专栏及课程。

余额充值