【C++学习第12天】(1)并查集

一、原理

并查集

        1.将两个集合合并;

        2.询问两个元素是否在一个集合中。

基本原理:每个集合用一棵树来表示,树根的编号就是整个集合的编号,每个节点存储它的父节点,p[x]表示 x 的父节点。

优化:路径压缩。

问题一:如何判断树根:if(p[x] == x)

问题二:如何求x的集合编号:while(p[x] != x)  x = p[x];

问题三:如何合并两个集合:px是x的集合编号,py是y的集合编号。p[x] = y。

二、代码

#include <iostream>
#include <cstring>
#include <vector>
using namespace std;

const int N = 100010;

int n, m;
int p[N];

int find(int x){	// 返回 x 的祖宗节点 + 路径压缩
	if(p[x] != x)
		p[x] = find(p[x]);
	return p[x];
}

int main(){
	scanf("%d%d", &n, &m);

	for(int i = 1; i <= n; i++)
		p[i] = i;
	
	while(m--){
		char op[2];	//scanf读入字符时不会忽略空格,读入字符串时会忽略空格。
		int a, b;
		scanf("%s%d%d", op, &a, &b);

		if(op[0] == 'M')
			p[find(a)] = find(b);
		else{
			if(find(a) == find(b))
				puts("Yes");
			else
				puts("No");
		}
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值