题意: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;
}