hdu1272 小希的迷宫 ——并查集无向图判环
May 12, 2013
Hdu
Data Structure
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1272 题目大意: 给一个无向图,判断是不是有环,有就输出No,否则输出Yes 题目思路: 用并查集,开始还天真地以为要用拓扑排序,好吧……虽然那个也可以做,可是为什么不用简单的方法呢?
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <algorithm>
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
using namespace std;
typedef long long int LL;
const int MAXN = 0x7fffffff;
const int MINN = -0x7fffffff;
const double eps = 1e-9;
const int dir[8][2] = {{0,1},{1,0},{0,-1},{-1,0},{-1,1},
{1,1},{1,-1},{-1,-1}};
const int MAX = 100000+10;
int parent[MAX];
bool flag;
void init() {
for (int i = 1; i<=MAX; ++i) parent[i] = -1;
}
int find(int x) {
int s;
for (s = x; parent[s] != s; s = parent[s]) ;
while (s != x) {
int tmp = parent[x]; parent[x] = s; x = tmp;
}
return s;
}
void Union(int R1, int R2) {
int r1 = find(R1), r2 = find(R2);
if (r1 != r2) parent[r1] = r2;
else flag = false;
}
int main(void){
#ifndef ONLINE_JUDGE
freopen("hdu1272.in", "r", stdin);
#endif
int a, b; bool re = true;
map<int, bool> mymap;
while (1) {
init(); flag = true;
mymap.clear();
while (~scanf("%d%d", &a, &b)) {
if (a == 0 && b == 0) break;
if (!mymap[a]) {parent[a] = a;mymap[a] = true;}
if (!mymap[b]) {parent[b] = b;mymap[b] = true;}
if (a == -1 && b == -1) {re = false; break;}
Union(a, b);
}
if (!re) break;
int cnt = 0;
for (int i = 1; i < MAX; ++i) {
if (mymap[i] && parent[i] == i) {
cnt++;
}
}
if (cnt > 1) flag = false;
if (flag) printf("Yes\n"); else printf("No\n");
}
return 0;
}
代码比较挫……也比较乱。。这题目就是输入的时候需要处理一下,别的没什么。