HDU1269 迷宫城堡

本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作。

本文作者:ljh2000
作者博客:http://www.cnblogs.com/ljh2000-jump/
转载请注明出处,侵权必究,保留最终解释权!

 
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
解题报告:
  tarjan算法裸题,check一下全图是否有且仅有一个强连通分量。
  联赛前复习模板...
 
 1 //It is made by ljh2000
 2 #include <iostream>
 3 #include <cstdlib>
 4 #include <cstring>
 5 #include <cstdio>
 6 #include <cmath>
 7 #include <algorithm>
 8 #include <ctime>
 9 #include <vector>
10 #include <queue>
11 #include <map>
12 #include <set>
13 #include <string>
14 using namespace std;
15 typedef long long LL;
16 const int MAXN = 10011; 
17 const int MAXM = 100011; 
18 int n,m,ecnt,first[MAXN],to[MAXM],NEXT[MAXM];
19 int dfn[MAXN],low[MAXN],cnt,zhan[MAXN],top;
20 bool pd[MAXN];
21 
22 inline int getint(){
23     int w=0,q=0; char c=getchar(); while((c<'0'||c>'9') && c!='-') c=getchar();
24     if(c=='-') q=1,c=getchar(); while (c>='0'&&c<='9') w=w*10+c-'0',c=getchar(); return q?-w:w;
25 }
26 
27 inline void tarjan(int x){
28     dfn[x]=low[x]=++ecnt; zhan[++top]=x; pd[x]=1;
29     for(int i=first[x];i;i=NEXT[i]) {
30         int v=to[i];    
31         if(!dfn[v]) tarjan(v),low[x]=min(low[x],low[v]);
32         else if(pd[v]) low[x]=min(low[x],dfn[v]);
33     }
34     if(dfn[x]==low[x]) {
35         cnt++;    while(zhan[top]!=x) pd[zhan[top]]=0,top--;
36         pd[x]=0; top--;
37     }
38 }
39 
40 inline void work(){
41     while(1) {
42         n=getint(); m=getint(); int x,y; if(n==0 && m==0) break;
43         memset(first,0,sizeof(first)); ecnt=0;
44         for(int i=1;i<=m;i++) {    x=getint(); y=getint();    NEXT[++ecnt]=first[x]; first[x]=ecnt; to[ecnt]=y; }
45         memset(dfn,0,sizeof(dfn)); memset(low,0,sizeof(low)); ecnt=0;
46         cnt=0; for(int i=1;i<=n;i++) if(!dfn[i]) tarjan(i);        
47         if(cnt!=1) printf("No
"); else printf("Yes
");
48     }
49 }
50 
51 int main()
52 {
53     work();
54     return 0;
55 }
原文地址:https://www.cnblogs.com/ljh2000-jump/p/6078182.html