迷宫城堡(HDU-1269)
生活随笔
收集整理的這篇文章主要介紹了
迷宫城堡(HDU-1269)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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
思路:實質是要判斷圖是否為一強連通圖,Tarjan 算法求強連通分量,判斷是否為1即可
Source Program
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<string> #include<cstdlib> #include<queue> #include<set> #include<map> #include<stack> #include<ctime> #include<vector> #define INF 0x3f3f3f3f #define PI acos(-1.0) #define N 20001 #define MOD 16007 #define E 1e-6 #define LL long long using namespace std; int n,m; vector<int> G[N]; stack<int> S; int dfn[N],low[N]; bool vis[N]; int sccno[N]; int block_cnt; int sig; void Tarjan(int x){vis[x]=true;dfn[x]=low[x]=++block_cnt;S.push(x);for(int i=0;i<G[x].size();i++){int y=G[x][i];if(vis[y]==false){Tarjan(y);low[x]=min(low[x],low[y]);}else if(!sccno[y])low[x]=min(low[x],dfn[y]);}if(dfn[x]==low[x]){sig++;while(true){int temp=S.top();S.pop();sccno[temp]=sig;if(temp==x)break;}} } int main() {while(scanf("%d%d",&n,&m)!=EOF&&(m+n)){for(int i=1;i<=n;i++)G[i].clear();while(m--){int x,y;scanf("%d%d",&x,&y);G[x].push_back(y);}sig=0;block_cnt=0;memset(vis,0,sizeof(vis));memset(dfn,0,sizeof(dfn));memset(low,0,sizeof(low));memset(sccno,0,sizeof(sccno));for(int i=1;i<=n;i++)if(vis[i]==false)Tarjan(i);if(sig==1)printf("Yes\n");elseprintf("No\n");} }?
總結
以上是生活随笔為你收集整理的迷宫城堡(HDU-1269)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 确定比赛名次(HDU-1285)
- 下一篇: 数论 —— 斐波那契数列(Fibonac