并查集

本文介绍了一种用于解决亲戚关系查询问题的并查集算法。该算法通过维护一系列的集合来实现成员之间的合并与查找操作,能够高效地判断任意两人间是否存在亲戚关系。输入包括个人数量、已知亲戚关系对及待查询的亲戚关系对;输出则是针对每组查询给出的真假判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

并查集分为——合并和查询的过程。

Description
若某个家族人员过于庞大,要判断两个是否是亲戚,确实还很不容易,现在给出某个亲戚关系图,求任意给出的两个人是否具有亲戚关系。 规定:x和y是亲戚,y和z是亲戚,那么x和z也是亲戚。如果x,y是亲戚,那么x的亲戚都是y的亲戚,y的亲戚也都是x的亲戚。
Input
第一行:三个整数n,m,p,(n<=5000,m<=5000,p<=5000),分别表示有n个人,m个亲戚关系,询问p对亲戚关系。 以下m行:每行两个数Mi,Mj,1<=Mi,Mj<=N,表示Ai和Bi具有亲戚关系。 接下来p行:每行两个数Pi,Pj,询问Pi和Pj是否具有亲戚关系。
Output
P行,每行一个’true’或’false’。表示第i个询问的答案为“具有”或“不具有”亲戚关系。
Sample Input
6 5 3
1 2
1 5
3 4
5 2
1 3
1 4
2 3
5 6
Sample Output
true
true
false

代码:

#include<iostream>
using namespace std;

const int MAX = 1000;
int parent[MAX];

int find(int target){
	int root = target , temp = target , t;
	while(parent[root] != root){
		root = parent[root];
	}
	while(parent[temp] != temp){
		t = parent[temp];
		parent[temp] = root;
		temp = t;
	}
	return root;
}

void Union(int a , int b){
	int parentA = find(a);
	int parentB = find(b);
	if(parentA != parentB){
		parent[parentB] = parentA;
	}
	return ;
}


int main(){
	int n , t;
	cin >> n >> t;
	for(int i = 0;i < MAX;i++){
		parent[i] = i;
	}
	int t1 , t2;
	for(int i = 0;i < n;i++){
		cin >> t1 >> t2;
		Union(t1 , t2);
	}
	for(int j = 0;j < t;j++){
		cin >> t1 >> t2;
		int parentA = find(t1);
		int parentB = find(t2);
		if(parentA == parentB){
			cout << "true" << endl;
		}else{
			cout << "false" << endl;
		}
	}
	return 0;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值