HDU - 1272 小希的迷宫 并查集模版

题目链接

HDU-1272

题意

给定若干边,问涉及到的点能否构成一个联通的,每两点间道路唯一的图

思路

并查集模版,每次接受u,v看uv是否在同一集合内,在的话两点间道路就不唯一了,不在就连接。
注意两点,一是最终需要是连通图,也就是 1 2 3 4 0 0这样的数据是No。二是没有边,也就是0 0的数据是Yes。

代码

#include<bits/stdc++.h>  
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define endl "\n"
using namespace std;
	typedef long long ll;
	const int maxn=100500;
	const int inf=0x3f3f3f3f;
	int n,m,q;
	int fa[maxn];
	bool uesd[maxn];
	int cnt,id;
	void init(){
		for(int i=0;i<maxn;i++){
			fa[i]=i;
		}
	}
	
	int find(int x){
		return x==fa[x]?x:fa[x]=find(fa[x]);
	}
	
	void unite(int u,int v){
		int fx=find(u),fy=find(v);
		if(fx==fy)
			return ;
		fa[fx]=fy;
		return ;
	}

	int main(){
		IOS
		int a,b;
		bool ans=0;
		init();
		while(cin>>a>>b){
			if(a==-1&&b==-1)
				break;
			if(!a&&!b){
				for(int i=1;i<maxn;i++){
					if(uesd[i]){
						if(!cnt){
							cnt++;
							id=find(i);
						}
						else{
							if(find(i)!=id)
								cnt++;
						}
					}
				}
				if(cnt>1)
					ans=1;
				if(ans)	
					cout<<"No"<<endl;
				else	
					cout<<"Yes"<<endl;
				ans=0;
				init();
				memset(uesd,0,sizeof uesd);
				cnt=0,id=0;
				continue;
			}
			uesd[a]=uesd[b]=1;
			int fx=find(a),fy=find(b);
			if(fx==fy)
				ans=1;
			else
				unite(a,b);
		}
	}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值