HDU 1272 小希的迷宫 (并查集判断回路、连通)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1272

数据的读入有些奇葩...题意就是给一个图,若有环或者不连通输出No,否则Yes。

参考博客:http://www.cnblogs.com/kuangbin/archive/2012/07/29/2613781.html


#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
int f[100100], p[100100], book[100100];
//  父节点     已出现的点   //该点是否出现过 
int find(int t) {
	if(f[t] == 0) return t;
	return f[t] = find(f[t]);
}
int main () {
	int a, b;
	while(scanf("%d %d", &a, &b)) {
		memset(p, 0, sizeof(p));
		memset(book, 0, sizeof(book));
		memset(f, 0, sizeof(f));
		if(a == -1 && b == -1) break;
		if(a == 0 && b == 0) {  //一个空图居然是Yes... 
			printf("Yes\n");
			continue;
		}
		f[a] = b;
		int cnt = 0;
		p[cnt++] = a;
		p[cnt++] = b;
		book[a] = 1, book[b] = 1;
		int flag = 0;
		while(scanf("%d %d", &a, &b)) {
			if(a == 0 && b == 0) break;
			if(flag) continue;
			int t1 = find(a);
			int t2 = find(b);
			if(t1 == t2) {  //说明有环,直接退出即可 
				flag = 1;
				continue;
			}
			f[t1] = t2;
			if(book[a] == 0) {
				book[a] = 1;
				p[cnt++] = a;
			}
			if(book[b] == 0) {
				book[b] = 1;
				p[cnt++] = b;
			}
		}
		if(flag == 0) {  //无环,判断是否连通 
			int num = 0;
			int i;
			for(i = 0; i < cnt; i++) {
				if(f[p[i]] == 0) {
					num++;
				}
			}
			if(num > 1) flag = 1;
		}
		if(flag) printf("No\n");
		else printf("Yes\n");
	}
	return 0;
}


你可能感兴趣的:(并查集,图)