迷宮城堡 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


模板題 
代碼如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<string>
#include<queue>
#include<vector>
#include<stack>
#include<list>
#include<map>
#include<set>
using namespace std;
const int maxn = 100000+5;
int Laxt[maxn],Next[maxn],To[maxn],cnt,n,m,ans;
int times,dfn[maxn],low[maxn],scc[maxn],scc_cnt;
int stc[maxn],top,instc[maxn];
void add(int u,int v)
{
    Next[++cnt]=Laxt[u];
    Laxt[u]=cnt;
    To[cnt]=v;
}
void init()
{
    top=cnt=scc_cnt=ans=0;
    memset(Laxt,0,sizeof(Laxt));
    memset(dfn,0,sizeof(dfn));
    memset(low,0,sizeof(low));
    memset(scc,0,sizeof(scc));
    memset(stc,0,sizeof(stc));
    memset(instc,0,sizeof(instc));
}
int dfs(int u)
{
    dfn[u]=low[u]=++times;
    stc[++top]=u;
    instc[u]=1;
    for(int i=Laxt[u]; i; i=Next[i])
    {
        int v=To[i];
        if(!dfn[v])
        {
            dfs(v);
            low[u]=min(low[u],low[v]);
        }
        else if(instc[v])
        {
            low[u]=min(low[u],low[v]);
        }
    }
    if(dfn[u]==low[u])
    {
        scc_cnt++;
        while(true)
        {
            int x=stc[top--];
            scc[x]=scc_cnt;
            instc[x]=0;
            if(x==u) break;
        }
    }
}
void tarjan()
{
    int i;
    for(i=1; i<=n; i++)
        if(!dfn[i]) dfs(i);
       if(scc_cnt==1) cout<<"Yes"<<endl;
       else cout<<"No"<<endl;
}
int main()
{
    while(scanf("%d %d",&n,&m),n+m)
    {
        init();
        int a,b;
        for(int i=1; i<=m; i++)
        {
            scanf("%d %d",&a,&b);
            add(a,b);
        }
        tarjan();
    }
}

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