hdu 1272 小希的迷宫 并查集

#include <cstdio>
#include <iostream>
#include <queue>
#include <set>
using namespace std;
struct node{
	int x,y;
};
int fa[100015];
int find(int x){
	while(fa[x]!=x){
		x = fa[x];
	}
	return x;
}
int d[100015];
node b[100015];

int unit(int x,int y){
	if(d[x] < d[y]){
		fa[x] = y;
	}
	else if(d[y] < d[x]){
		fa[y] = x;
	}
	else{
		fa[x] = y;
		d[x] ++;
	}
}

int main(){
	node a;
	
	while(scanf("%d%d",&a.x,&a.y)){
		if(a.x == -1&& a.y ==-1)break;
		
		int ma = 0;
		int cc = 0;
		b[cc] = a;
		
		
		while(b[cc].x || b[cc].y){
			cc++;
			scanf("%d%d",&b[cc].x,&b[cc].y);
			ma = max(ma,max(b[cc].x,b[cc].y));
		} 
		for(int i = 0;i <= ma+1;i++){
			fa[i] = i;
			d[i] = 1;
		}
		
		int flag = 1;
		int j = 0;
		while(j < cc){
			a = b[j];
			int fx = find(a.x);
			int fy = find(a.y);
			if(fx == fy){
				flag = 0;
				break;
			}
			else{
				unit(fx,fy);
			}
			j++;
		}
		
		if(flag){
			set<int>  se;
			for(int i = 0;i < cc && se.size() <= 1;i++){
				se.insert(find(b[i].x));
				se.insert(find(b[i].y));
			}
			
			if(se.size() <= 1){
				cout << "Yes" << endl;
			}
			else{
				cout << "No" << endl;
			}
		}
		else{
			cout << "No" << endl;
		}
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值