迷宫城堡(HDU-1269)
生活随笔
收集整理的這篇文章主要介紹了
迷宫城堡(HDU-1269)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Problem Description
為了訓(xùn)練小希的方向感,Gardon建立了一座大城堡,里面有N個(gè)房間(N<=10000)和M條通道(M<=100000),每個(gè)通道都是單向的,就是說(shuō)若稱某通道連通了A房間和B房間,只說(shuō)明可以通過(guò)這個(gè)通道由A房間到達(dá)B房間,但并不說(shuō)明通過(guò)它可以由B房間到達(dá)A房間。Gardon需要請(qǐng)你寫個(gè)程序確認(rèn)一下是否任意兩個(gè)房間都是相互連通的,即:對(duì)于任意的i和j,至少存在一條路徑可以從房間i到房間j,也存在一條路徑可以從房間j到房間i。
Input
輸入包含多組數(shù)據(jù),輸入的第一行有兩個(gè)數(shù):N和M,接下來(lái)的M行每行有兩個(gè)數(shù)a和b,表示了一條通道可以從A房間來(lái)到B房間。文件最后以兩個(gè)0結(jié)束。
Output
對(duì)于輸入的每組數(shù)據(jù),如果任意兩個(gè)房間都是相互連接的,輸出"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
思路:實(shí)質(zhì)是要判斷圖是否為一強(qiáng)連通圖,Tarjan 算法求強(qiáng)連通分量,判斷是否為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");} }?
總結(jié)
以上是生活随笔為你收集整理的迷宫城堡(HDU-1269)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 确定比赛名次(HDU-1285)
- 下一篇: 数论 —— 斐波那契数列(Fibonac