CodeForces 566D Restructuring Company (并查集)

题意:n个元素,三种操作,第一种将x和y连起来,第二种将[x, y]内所有元素连起来,第三种查询元素x和y是否属于同一集合。

题解:并查集
主要是第二种操作,我们用a[]记录连续区间的右端点,相当于把整个连续点集合当作一个点。

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
const int Max = 2e5 + 5;
int Parent[Max], Rank[Max], rep[Max], cnt;
int Find(int x) {
	return Parent[x] == x ? x : Parent[x] = Find(Parent[x]);
}
void Union(int x, int y) {
	int u, v, root;
	u = Find(x);
	v = Find(y);
	if (u == v) {
		return;
	}
	Parent[v]=u;
 
}
int n, q, t, x, y, a[Max];
int main() {
	scanf("%d%d", &n, &q);
	for (int i = 1; i <= n; i++) Parent[i] = i, a[i] = i;
	while (q--) {
		scanf("%d%d%d", &t, &x, &y);
		if (t == 1) {
			Union(x, y);
		}
		else if (t == 2) {
			int temp;
			a[x] = a[y];
			for (int i = x; i < y; i = temp) {
				Union(i, i + 1);
				temp = a[i + 1];
				a[i + 1] = a[y];
			}
		}
		else {
			printf("%s\n", Find(x) == Find(y) ? "YES" : "NO");
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值