HDU 1269 迷宫城堡 -- 强连通图判断

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1269

图的强连通分量
http://baike.baidu.com/link?url=NqsmNsGCotb9HUFgYdX1glgerL2cNjCe_OANCijjZLm8bjtmgrQ3DCPwNqMZz-S1GJ8lyAKPLDck8t5hsKXp2a
kosaraju算法
http://baike.baidu.com/link?url=JAN1OaKp_iwWknC2Q8NuQNT3hXnEm13kQaXKI724FjtjeGcrj90H4vAb-n7VMpOZ7zakYGhCwLg58Ad5AOnq5a

/* 迷宫城堡 http://acm.hdu.edu.cn/showproblem.php?pid=1269 */
#include<stdio.h> 
#include<stdlib.h>
#include<vector>
#include<iostream>
#include<stack>
using namespace std;

#define N 10005
int n , m ;
vector<int> v[N] ,r_v[N]; // 原图 和 逆向图

int cnt ;
bool visit[N];
bool flag ;

bool dfs(int rt,vector<int> *graph)
{
    stack<int> sta;
    sta.push(rt);
    visit[rt] = true;
    cnt = 0 ;

    while(!sta.empty())
    {
        int now_u = sta.top();
        cnt++;
        sta.pop();
        for(int i= 0 ; i < (int)graph[now_u].size() ; i++)
        {
            if( !visit[graph[now_u][i]])
            {
                sta.push(graph[now_u][i]);
                visit[graph[now_u][i]] = true;
            }
        }
    }
    if(cnt == n )
        return true;
    return false;
}

bool kosaraju()  
{  
    memset(visit, 0, sizeof(visit));  
    bool ret = dfs(1, v);  
    if (!ret)
        return false;  
    memset(visit, 0, sizeof(visit));  
    ret = dfs(1, r_v);  
    if (ret)
        return true;  
    return false;  
}  

int main()  
{  
    //freopen("in.txt","r",stdin);
    int i,j;  
    while(scanf("%d%d",&n,&m) != EOF)  
    { 
        if(n == 0 && m == 0 )
            break;
        int a , b;
        for(i = 1; i <= n ; i++)
        {
            v[i].clear();
            r_v[i].clear();
        }
        for(i = 0; i < m ; i++)
        {
            scanf("%d%d",&a,&b);
            v[a].push_back(b);
            r_v[b].push_back(a);
        }
        if(kosaraju())
              printf("Yes\n");  
        else  
            printf("No\n");  
    }  
    return 0;  
}

你可能感兴趣的:(HDU 1269 迷宫城堡 -- 强连通图判断)