hdu1269 迷宮城堡

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

Source

HDU 2006-4 Programming Contest

// 強連通分量模板題

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<stack>
#include<cstring>
#include<vector>
using namespace std;
const int maxn = 20000;
vector<int> E[maxn];
int low[maxn],dfn[maxn],vis[maxn],tot,ans;
stack<int>st;
void tarjan(int x)
{
    dfn[x] = low[x] = ++ tot;
    vis[x] = 1;
    st.push(x);
    for(int i=0;i<E[x].size();i++)
    {
        int v = E[x][i];
        if(!dfn[v])
        {
            tarjan(v);
            low[x] = min(low[x],low[v]);
        }
        else if(vis[v]==1)
        {
            low[x] = min(low[x],dfn[v]);
        }
    }
    if(low[x] == dfn[x])
    {
        ans ++;
        while(1)
        {
            int now = st.top();st.pop();
            vis[now] = 0;
            if(now == x) break;
        }
    }
}
int main()
{
    int n,m;

    while(cin >> n >> m)
    {
        
        tot = 0;
        memset(low,0,sizeof(low));
        memset(dfn,0,sizeof(dfn));
        memset(vis,0,sizeof(vis));
        ans = 0; 
        for(int i=0;i<=n;i++)
            E[i].clear();
        while(!st.empty()) st.pop();
        if(n==0&&!m) break;


        for(int i=1;i<=m;i++)
        {
            int u,v;
            scanf("%d %d",&u,&v);
            E[u].push_back(v);
        }
        for(int i=1;i<=n;i++)
            if(!dfn[i])
                tarjan(i);
        
        if(ans == 1) cout << "Yes" <<endl;
        else cout << "No"<<endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章