迷宫城堡
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10075 Accepted Submission(s): 4529Problem 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 Input3 31 22 33 13 31 22 33 20 0Sample OutputYesNoAuthorGardonSource
模板~
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 #include <algorithm> 6 #define ll long long 7 using namespace std; 8 const int MAXN = 12000; 9 const int MAXM = 120000; 10 struct Edge 11 { 12 int to,next; 13 }edge[MAXM]; 14 int head[MAXN],tot; 15 int Low[MAXN],DFN[MAXN],Stack[MAXN],Belong[MAXN]; 16 int Index,top; 17 int scc; 18 bool Instack[MAXN]; 19 int num[MAXN]; 20 21 void addedge(int u,int v) 22 { 23 edge[tot].to = v;edge[tot].next = head[u];head[u] = tot++; 24 } 25 void Tarjan(int u) 26 { 27 int v; 28 Low[u] = DFN[u] = ++Index; 29 Stack[top++] = u; 30 Instack[u] = true; 31 for(int i = head[u]; i != -1; i = edge[i].next) 32 { 33 v = edge[i].to; 34 if( !DFN[v] ) 35 { 36 Tarjan(v); 37 if(Low[u] > Low[v]) Low[u] = Low[v]; 38 } 39 else if(Instack[v] && Low[u] > DFN[v]) 40 Low[u] = DFN[v]; 41 } 42 if(Low[u] == DFN[u]) 43 { 44 scc++; 45 do 46 { 47 v = Stack[--top]; 48 Instack[v] = false; 49 Belong[v] = scc; 50 num[scc]++; 51 } 52 while(v != u); 53 } 54 } 55 void solve(int N) 56 { 57 memset(DFN,0,sizeof(DFN)); 58 memset(Instack,false,sizeof(Instack)); 59 memset(num,0,sizeof(num)); 60 Index = scc = top = 0; 61 for(int i = 1; i <= N; i++) 62 if( !DFN[i]) 63 Tarjan(i); 64 } 65 void init() 66 { 67 tot = 0; 68 memset(head,-1,sizeof(head)); 69 } 70 int main(void) 71 { 72 int n,m,a,b; 73 while(scanf("%d %d",&n,&m) ,n != 0 || m != 0) 74 { 75 init(); 76 for(int i = 0; i < m; i++) 77 { 78 scanf("%d %d",&a,&b); 79 addedge(a,b); 80 } 81 solve(n); 82 if(scc == 1) 83 printf("Yes "); 84 else 85 printf("No "); 86 } 87 return 0; 88 }