【解题报告】 HDU 1272 小希的迷宫 并查集 判连通+判环

题目连接: HDU 1272
这个主要是 图的判连通 和 判不存在环 即可。也属于水题。第一次使用了递归压缩路径,纪念一下。
// HDU 1272 小希的迷宫 并查集 判连通+判环
//测试数据:
//1 2  2 3  4 5  0 0
//0 0
//6 8  5 3  5 2  6 4  5 6  0 0
//8 1  7 3  6 2  8 9  7 5  7 4  7 8  7 6  0 0
//3 8  6 8  6 4  5 3  5 6  5 2  0 0
//1 2  2 3  3 4  4 5  5 6  6 1  0 0
//1 2  1 2  0 0
//-1 -1
#include <cstdio>
#include <iostream>
#include <cstring>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;

const int MAXP = 100005;
bool flag;
int father[MAXP];

void init(){
	memset(father,-1,sizeof(father));
	flag = true;
}

int find(int a){
	if (father[a] <= 0)		return a;
	return father[a] = find(father[a]);
}

void combination(int ra,int rb){
	father[rb] = ra; //father[rb]一定为 0 或 -1
	if ( father[ra] < 0 )
		father[ra] = 0; // 只有-1有资格变成0
}

bool is_connected(){
	int s=0;
	for (int i =1; i < MAXP; i++)
		if (father[i]==0)
			s++;
	if (s>1)return false;
	else	return true;
}

int main()
{
//	freopen("in.txt","r",stdin);
	while(1){
		int a,b,l=0;
		init();
		while(scanf("%d%d",&a,&b)&&a!=-1){
			if (a<=0 && b<=0){
				if (l==0)
					flag = true;
				break;
			}else{
				int ra = find(a);
				int rb = find(b);
				if (ra == rb){ // they have same ancestor
					flag = false;
				}else{
					combination(ra,rb);
				}
			}l++;
		}
		if (a==-1)break;
		if (flag && is_connected()){
			cout << "Yes" << endl;
		}else{
			cout << "No" << endl;
		}
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值