HDU1269 迷宫城堡(强连通图+Tarjan)

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
 
判断每一组数据的图是不是强连通图
转化为统计强连通分量的个数是不是为1
 
 
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <vector>
 4 #include <algorithm>
 5 #include <iostream>
 6 using namespace std;
 7 
 8 const int N=1e5+5;
 9 int low[N],dfn[N],Stack[N];
10 bool inStack[N];
11 vector<int> g[N];
12 int tot,top,n,m,cnt;
13 
14 void init(){
15     tot=top=cnt=0;
16     memset(low,0,sizeof low);
17     memset(dfn,0,sizeof dfn);
18     memset(Stack,0,sizeof Stack);
19     memset(inStack,false,sizeof inStack);
20     for(int i=0;i<N;i++){
21         g[i].clear();
22     }
23 }
24 
25 void tarjan(int u){
26     int v;
27     dfn[u]=low[u]=++tot;
28     Stack[++top]=u;
29     inStack[u]=true;
30     for(int i=0;i<g[u].size();i++){
31         v=g[u][i];
32         if(dfn[v]==0){
33             tarjan(v);
34             low[u]=min(low[u],low[v]);
35         }
36         else{
37             low[u]=min(low[u],dfn[v]);
38         }
39     }
40     if(dfn[u]==low[u]){
41         cnt++;
42         do{
43             v=Stack[top--];
44             inStack[v]=false;
45         }while(u!=v);
46     }
47 }
48 
49 int main(){
50     int x,y;
51     while(scanf("%d%d",&n,&m),n||m){
52         init();
53         while(m--){
54             scanf("%d%d",&x,&y);
55             g[x].push_back(y);
56         }
57         for(int i=1;i<=n;i++){
58             if(dfn[i]==0){
59                 tot=0;
60                 tarjan(i);
61             }
62         }
63         if(cnt==1) printf("Yes
");
64         else printf("No
");
65     }
66 }
原文地址:https://www.cnblogs.com/ChangeG1824/p/11415925.html