標籤:acm tarjan
迷宮城堡
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8099 Accepted Submission(s): 3623
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 31 22 33 13 31 22 33 20 0
Sample Output
YesNo
Author
Gardon
Source
HDU 2006-4 Programming Contest
代碼:
#include <iostream>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <algorithm>#include <vector>#include <queue>#include <stack>#include <map>#include <set>#include <cmath>#include <time.h>#include <iomanip>#include <cctype>#define ll long longusing namespace std;/**Tarjan 演算法複雜度O(n+m)*/const int maxn=10010;///點數const int maxm=100010;///邊數struct Edge{ int to,next;}edge[maxm];///每條邊看做一個結構體int head[maxn],tot;int low[maxn],dfn[maxn],Stack[maxn],belong[maxn];///dfn[i]表示搜尋時第i個頂點的訪問時間,low[i]表示第i個頂點或者其子樹中節點的最小訪問時間///Belong[i]表示第i個頂點屬於哪一個強連通分量中,數組的值為1~scc,共有scc個強連通分量int index,top;///index用來搜尋時添加頂點訪問時間,top棧頂int scc;///強連通分量的個數bool instack[maxn];///判斷頂點i是否在棧中int num[maxn];///各個強連通分量包含點的個數,數組編號1~sccvoid addedge(int u,int v)///增加一條邊,由u指向v,鄰接表的實現採用頭插法{ edge[tot].to=v; edge[tot].next=head[u]; head[u]=tot++;}void Tarjan(int u){ int v; low[u]=dfn[u]=++index;///一開始訪問時間等於最小時間 Stack[top++]=u;///入棧 instack[u]=true; for(int i=head[u];i!=-1;i=edge[i].next)///與u相鄰的頂點v,由u指向v { v=edge[i].to; if(!dfn[v]) { Tarjan(v); if(low[u]>low[v]) low[u]=low[v]; } else if(instack[v]&&low[u]>dfn[v]) low[u]=dfn[v]; } if(low[u]==dfn[u]) { scc++; do { v=Stack[--top]; instack[v]=false; belong[v]=scc; num[scc]++; }while(v!=u); }}void init(){ tot=0; memset(head,-1,sizeof(head));}void solve(int n){ memset(dfn,0,sizeof(dfn)); memset(instack,false,sizeof(instack)); memset(num,0,sizeof(num)); index=scc=top=0; for(int i=1;i<=n;i++) if(!dfn[i]) Tarjan(i);}int n,m;int u,v;int main(){ while(scanf("%d%d",&n,&m)!=EOF&&(n||m)) { init(); while(m--) { scanf("%d%d",&u,&v); addedge(u,v); } solve(n); if(scc==1) cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0;}
[ACM] HDU 1269 迷宮城堡(Tarjan演算法求強聯通分量)