码迷,mamicode.com
首页 > 编程语言 > 详细

(tarjan算法) hdu 1269

时间:2015-03-18 15:20:00      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

迷宫城堡

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


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
 

 

Author
Gardon
 

 

Source
 

 

 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<vector>
#include<stack>
using namespace std;
#define maxn 10000+10
vector<int> mp[maxn];
stack<int> s;
int n,m,Dfs[maxn],low[maxn];
bool isstack[maxn];
int use[maxn];
int top,newflag;
void init()
{
    memset(isstack,0,sizeof(isstack));
    memset(use,0,sizeof(use));
    memset(Dfs,0,sizeof(Dfs));
    memset(low,0,sizeof(low));
    for(int i=0;i<maxn;i++)
        mp[i].clear();
    while(!s.empty())
        s.pop();
    newflag=0;
    top=0;
}
void tarjan(int u)
{
    Dfs[u]=low[u]=++top;
    isstack[u]=1;
    s.push(u);
    for(int x=0;x<mp[u].size();x++)
    {
        int v=mp[u][x];
        if(!Dfs[v])
        {
            tarjan(v);
            if(low[v]<low[u])
                low[u]=low[v];
        }
        else if(isstack[v]&&Dfs[v]<low[u])
        {
            low[u]=Dfs[v];
        }
    }
    if(Dfs[u]==low[u])
    {
        newflag++;
        int x;
        do
        {
            x=s.top();
            isstack[x]=0;
            use[x]=newflag;
            s.pop();
        }while(x!=u);
    }
    return ;
}
int main()
{
    int x,y;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        if(n==0&&m==0)
            break;
        init();
        for(int i=1;i<=m;i++)
        {
            scanf("%d%d",&x,&y);
            mp[x].push_back(y);
        }
        for(int i=1;i<=n;i++)
        {
            if(!Dfs[i])
                tarjan(i);
        }
        if(newflag==1)
        {
            printf("Yes\n");
        }
        else
            printf("No\n");
    }
    return 0;
}

  

  

(tarjan算法) hdu 1269

标签:

原文地址:http://www.cnblogs.com/a972290869/p/4346957.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!