HDU1269 迷宫城堡

Time Limit: 1000MS   Memory Limit: 32768KB   64bit IO Format: %I64d & %I64u

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
 

Source

HDU 2006-4 Programming Contest

Tarjan算法模板题

求强连通分量

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<vector>
 5 #include<cstring>
 6 using namespace std;
 7 const int mxn=12000;
 8 int top,stack[mxn];//
 9 bool inst[mxn];//在栈内标志 
10 int cnt,dnow;//强连通个数,当前时间 
11 int dfn[mxn],low[mxn];
12 vector<int> e[mxn];//邻接矩阵 
13 void clear(){//初始化 
14     cnt=0;dnow=0;top=0;
15     memset(dfn,-1,sizeof(dfn));
16     memset(inst,false,sizeof(inst));
17     for(int i=1;i<mxn;i++) e[i].clear();
18 }
19 int n,m;
20 void tarjan(int s){//tarjan算法,s为源点
21     int v=0,i;
22     dfn[s]=++dnow;//标记当前节点的首次到达时间 
23     low[s]=dfn[s];//标记当前节点的最短到达时间 
24     inst[s]=true; 
25     stack[++top]=s;//当前节点入栈 
26     int si=e[s].size();
27     for(i=0;i<si;i++){
28         v=e[s][i];//到达点
29         if(dfn[v]==-1){
30             tarjan(v);
31             low[s]=min(low[v],low[s]);
32         }
33         else if(inst[v]){
34             low[s]=min(dfn[v],low[s]);
35         }
36     }
37     if(dfn[s]==low[s]){
38         cnt++;
39         do{
40             v=stack[top--];
41             inst[v]=false;
42         }while(s!=v);
43     }
44     return;
45 }
46 int main(){
47     while(scanf("%d%d",&n,&m)!=EOF){
48         if(n==0 && m==0)break;
49         clear();
50         int i,j;
51         int u,v;
52         for(i=1;i<=m;i++){
53             scanf("%d%d",&u,&v);
54             e[u].push_back(v);
55         }
56         for(i=1;i<=n;i++){
57             if(dfn[i]==-1)tarjan(i);
58         }
59         if(cnt==1)printf("Yes
");
60         else printf("No
");
61     }
62     return 0;
63 }

迷宫城堡

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11899    Accepted Submission(s): 5335


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
 
Author
Gardon
 
Source
 
Recommend
lxj
原文地址:https://www.cnblogs.com/SilverNebula/p/5554069.html