迷宫城堡//强连通分支Tarjan

题目:

 

迷宫城堡

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 20588    Accepted Submission(s): 8962

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 <vector>
using namespace std;
const int size = 1e4 + 1;

vector<int> graph[size];//存图
int dfn[size];
int t = 0;
int low[size];
int stack[size];
int pos = 0;//用于栈的索引
bool onstack[size];//是否在栈
bool marked[size];
int ans = 0;//连通分支数

void init(int N)//初始化
{
    t = 0;
    pos = 0;
    ans = 0;
    for(int i = 1; i <= N; i++)
    {
        graph[i].clear();
        onstack[i] = false;
        marked[i] = false;
    }
}

void Tarjan(int x)
{
    marked[x] = true;
    low[x] = dfn[x] = t++;
    onstack[x] = true;
    stack[pos++] = x;
    for(int i = 0; i < graph[x].size(); i++)
    {
        if(!marked[graph[x][i]])//未标记
        {
            Tarjan(graph[x][i]);
            if(low[graph[x][i]] < low[x])
                low[x] = low[graph[x][i]];//!!!
        }
        //在栈内
        else if(onstack[graph[x][i]] && dfn[graph[x][i]] < low[x])
            low[x] = dfn[graph[x][i]];//!!!
    }
    if(dfn[x] == low[x])//强连通分支的根
    {
        ans++;
        while(stack[--pos] != x)//出栈
        {
            int c = stack[pos];
            onstack[c] = false;
        }
        onstack[x] = false;
    }
}

int main()
{
    int N=1, M;
    int a, b;
    while(cin >> N >> M && N != 0 || M != 0)
    {
        //初始化
        init(N);
        //输入
        for(int i = 0; i < M; i++)
        {
            cin >> a >> b;
             graph[a].push_back(b);    
        }

        for(int i = 1; i <= N; i++)
        {
            if(!marked[i])
                Tarjan(1);
        }

        if(ans == 1)
            printf("Yes\n");
        else 
            printf("No\n");
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9218975.html
今日推荐