Step1 Problem:
n 个人,初始每个人都属于自己的部门,q 次操作
三种操作:
1 :x 所在部门和 y 所在部门合并
2 :合并 x, x+1, ….. y-1, y(也就是合并 x 到 y 全部)的部门
3 :询问 x, y 是否属于同一个部门
数据范围:
1<=n<=200000, 1<=q<=500000.
Step2 Ideas:
核心需要解决 2 操作:
如果对于每次询问都直接合并,O(n*q) 肯定超时,对于每次新的询问,有很多人已经在同一个部门了。
所以我们可以记录每个人右边哪个人可能不是同一个部门,这样中间过程的人,就没必要再合并了。
Step3 Code:
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5+5;
int f[N], n, nex[N];
void init()
{
for(int i = 0; i <= n; i++)
f[i] = i, nex[i] = i;
}
int Find(int x)
{
if(x == f[x]) return x;
else return f[x] = Find(f[x]);
}
void Merge(int x, int y)
{
x = Find(x); y = Find(y);
if(x != y) f[y] = x;
}
int main()
{
int q;
scanf("%d %d", &n, &q);
init();
int op, x, y;
while(q--)
{
scanf("%d %d %d", &op, &x, &y);
if(op == 1) Merge(x, y);
else if(op == 2) {
int to;
for(int i = x; nex[i]+1 <= y; i = to)
{
to = nex[i]+1;
Merge(to, i);
nex[i] = y;
}
}
else {
if(Find(x) == Find(y)) printf("YES\n");
else printf("NO\n");
}
}
return 0;
}