HDU 1269 迷宮城堡【Tarjan強連通分量 模板】

迷宮城堡

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


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


原題鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1269

題意:判斷圖的強連通分量是否爲一.模板題.

Targan算法介紹及模板:http://blog.csdn.net/hurmishine/article/details/75248876


AC代碼:

/**
  * 行有餘力,則來刷題!
  * 博客鏈接:http://blog.csdn.net/hurmishine
  * 個人博客網站:http://wuyunfeng.cn/
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
const int maxn=10000+5;
vector<int>G[maxn];

int n,m;
int index;
int cnt;
int low[maxn],dfn[maxn];
bool vis[maxn];//是否在棧裏


void Init()
{
    cnt=index=0;
    for(int i=0;i<=n;i++)
        low[i]=dfn[i]=0;
}
void Tarjan(int u)
{
    stack<int>s;
    s.push(u);
    vis[u]=true;
    low[u]=dfn[u]=++index;
    for(int i=0;i<G[u].size();i++)
    {
        int v = G[u][i];
        if(!dfn[v])
        {
            Tarjan(v);
            low[u] = min(low[u],low[v]);
        }
        else if(vis[v])
        {
            low[u] = min(low[u],dfn[v]);
        }
    }
    if(low[u] == dfn[u])
    {
        cnt++;
        int x;
        do
        {
            x = s.top();
            s.pop();
            vis[x]=false;
        }while(x!=u);
    }
}
int main()
{
    //freopen("C:\\Documents and Settings\\Administrator\\桌面\\data.txt","r",stdin);
    while(cin>>n>>m,n+m)
    {
        for(int i=0;i<=n;i++)
            G[i].clear();
        int x,y;
        while(m--)
        {
            scanf("%d%d",&x,&y);
            G[x].push_back(y);
        }
        Init();
        for(int i=1;i<=n;i++)
        {
            if(!dfn[i])
               Tarjan(i);
        }
        if(cnt == 1)
            cout<<"Yes"<<endl;
        else
            cout<<"No"<<endl;
    }
    return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章