hdoj1269-迷宫城堡(tarjan)
2016-10-18 15:50
274 查看
题目链接
1 2
2 3
3 1
3 3
1 2
2 3
3 2
0 0
No
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 2
2 3
3 1
3 3
1 2
2 3
3 2
0 0
Sample Output
YesNo
思路
此题主要是给出一个图,然后求强连通分量的个数,就是tarjan算法的模板题.code
#include <iostream> #include <cstring> #include <fstream> #include <vector> #include <algorithm> using namespace std; const int MAX = 10000+5; bool in[MAX]; //当前节点是否在栈中 int low[MAX]; //当前节点根节点被遍历的时间点 int dfn[MAX]; //当前节点被遍历的时间点 int STACK[MAX]; int time; //time为访问的时间 int n, m, top; //top为栈顶元素位置 int cnt; //用来记录强连通分量的数目 vector<vector<int> > v(MAX); //记录边 void tarjan(int a) { in[a] = true; dfn[a] = low[a] = time++; STACK[top++] = a; for(int i = 0; i < v[a].size(); ++ i) { int temp = v[a][i]; if(!dfn[temp]) { tarjan(temp); low[a] = min(low[a], low[temp]); } else if(in[temp]) { low[a] = min(low[a], dfn[temp]); } } v[a].clear(); //注意清空,不然测试第二组数据会出错 if(low[a] == dfn[a]) { int j; cnt ++; do { j = STACK[top]; in[j] = false; top --; } while(j != a); } } int main() { //ifstream cin("data.in"); while(cin >> n >> m && (n || m)) { for(int i = 0; i < m; i ++) { int x, y; cin >> x >> y; v[x].push_back(y); } memset(in, false, sizeof(in)); memset(dfn, 0, sizeof(dfn)); time = 0; top = 0; cnt = 0; for(int i = 1; i <= n; i ++) { if(dfn[i] == 0) //有的图不是强连通分量 { tarjan(i); } } if(cnt == 1) { cout << "Yes" << endl; } else { cout << "No" << endl; } } return 0; }
相关文章推荐
- 迷宫城堡--HDOJ 1269(Tarjan)
- [置顶] HDOJ 1269 迷宫城堡 (Tarjan + 强连通分量)
- hdu1269迷宫城堡 (强连通Tarjan+邻接表)
- HDU - 1269 迷宫城堡-tarjan-有向图强连通分量
- 迷宫城堡 HDU - 1269 (tarjan)
- hdu 1269 迷宫城堡(tarjan 算法)
- hdu 1269 迷宫城堡(Tarjan 图的强连通分量)
- 迷宫城堡 HDU - 1269(tarjan求强联通)
- [ACM] HDU 1269 迷宫城堡(Tarjan算法求强联通分量)
- hdoj 1269 迷宫城堡 【有向图SCC 入门题目】
- 迷宫城堡 HDU - 1269(tarjan求强联通)
- HDOJ-1269 迷宫城堡
- HDU 1269:迷宫城堡 (Tarjan强连通分量)
- hdu 1269 迷宫城堡【强连通Tarjan】
- HDOJ1269(迷宫城堡)
- HDOJ 题目1269迷宫城堡(并查集)
- hdu 1269 迷宫城堡(tarjan模版)
- 迷宫城堡 HDU - 1269(tarjan求强联通)
- HDU1269——Tarjan——迷宫城堡
- 【强连通分量】 HDOJ 1269 迷宫城堡