HDU - 1269 ——迷宫城堡(强连通图的Tarjan算法)

为了训练小希的方向感,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

思路:本题为强连通图的算法题,属于图论的 Tarjan。也可以使用最短路,不过最短路的时间复杂度比较高。
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<vector>
#include<stack>
#define M 10010
using namespace std;
vector<int>q[M];
vector<int>com[M];
stack<int>qaq;
int DFN[M],book[M],LOW[M],ans[M];
int carry,indox,tem;
int n,m,x,y;
void init()
{
    memset(DFN,-1,sizeof(DFN));
    memset(book,0,sizeof(book));
    memset(LOW,-1,sizeof(LOW));
    carry=indox=0;
    for(int i=1; i<=n; i++)
    {
        q[i].clear();
    }
    while(!qaq.empty())
    {
        qaq.pop();
    }
    for(int i=1; i<=n; i++)
    {
        com[i].clear();
    }
}
void tarjan(int z)
{
    DFN[z]=LOW[z]=carry++;
    book[z]=1;
    qaq.push(z);
    for(int i=0; i<q[z].size(); i++)
    {
        tem=q[z][i];
        if(DFN[tem]==-1)
        {
            tarjan(tem);
            LOW[z]=min(LOW[z],LOW[tem]);
        }
        else if(book[tem])
        {
            LOW[z]=min(LOW[z],DFN[tem]);
        }
    }
    if( DFN[z]==LOW[z])
    {
        indox++;
        while(!qaq.empty())
        {
            tem=qaq.top();
            ans[tem]=indox;
            book[tem]=0;
            com[z].push_back(tem);
            qaq.pop();
        }
    }
}
int main()
{
    while(~scanf("%d%d",&n,&m),n||m)
    {
        init();
        for(int i=0; i<m; i++)
        {
            scanf("%d%d",&x,&y);
            q[x].push_back(y);
        }
        for(int i=1; i<=n; i++)
        {
            if(DFN[i]==-1)
                tarjan(i);
        }
        if(indox==1)
            printf("Yes\n");
        else
            printf("No\n");
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41380961/article/details/80055282