【题目链接】点击打开链接

【题意】

  题意  

给出 n 个元素,q 次操作,操作类型有三种

1 x y :将x 和 y 合并到一个集合

2 x y : 将x,x+1,x+2,...,y 合并到一个集合

3 x y : 询问x 和 y 是否处于同一个集合

  数据  

1 <= n <= 200000,1<=q<=500000

接下来q行每行三个整数 type x y (1 <= x,y <= n),注意在任何一种操作中 x 都有可能等于 y

  输入  

8 6

3 2 5

1 2 5

3 2 5

2 4 7

2 1 2

3 1 7

  输出  

NO

YES

YES


【解题方法】单点合并,这个可以用并查集轻松搞定,那么成段合并呢?注意到这个题只有合并,意思就是说我们用set 来搞的话,合并之后删除对应点,那么这样做的复杂度有保证吗?注意到一共有n个点,每个点最多只能进和出set一次,那么这样的复杂度可以保证是O(n * logn)的。那么查询段的位置,我们可以在set里面二分即可。


【AC代码】


//
//Created by BLUEBUFF 2016/1/9
//Copyright (c) 2016 BLUEBUFF.All Rights Reserved
//

#pragma comment(linker,"/STACK:102400000,102400000")
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/hash_policy.hpp>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#include <cstdio>
#include <time.h>
#include <cstdlib>
#include <cstring>
#include <sstream> //isstringstream
#include <iostream>
#include <algorithm>
using namespace std;
//using namespace __gnu_pbds;
typedef long long LL;
typedef pair<int, LL> pp;
#define REP1(i, a, b) for(int i = a; i < b; i++)
#define REP2(i, a, b) for(int i = a; i <= b; i++)
#define REP3(i, a, b) for(int i = a; i >= b; i--)
#define CLR(a, b)     memset(a, b, sizeof(a))
#define MP(x, y)      make_pair(x,y)
const int maxn = 200010;
const int maxm = 2e5;
const int maxs = 10;
const int maxp = 1e3 + 10;
const int INF  = 1e9;
const int UNF  = -1e9;
const int mod  = 1e9 + 7;
//int gcd(int x, int y) {return y == 0 ? x : gcd(y, x % y);}
//typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>order_set;
//head
set <int> s;
set <int>::iterator it1, it2;
int fa[maxn];
int find_set(int x){
    if(x == fa[x]) return x;
    return fa[x] = find_set(fa[x]);
}
void union_set(int x, int y){
    int fx = find_set(x), fy = find_set(y);
    if(fx != fy) fa[fx] = fy;
}
int main()
{
    int n, q;
    while(scanf("%d%d", &n, &q) != EOF)
    {
        s.clear();
        REP2(i, 1, n) fa[i] = i, s.insert(i);
        while(q--){
            int cmd, x, y;
            scanf("%d%d%d", &cmd, &x, &y);
            if(cmd == 1){
                union_set(x, y);
            }
            else if(cmd == 2){
                it1 = s.upper_bound(x);
                while(it1 != s.end() && *it1 <= y){
                    union_set(x, *it1);
                    it2 = it1++;
                    s.erase(it2);
                }
            }
            else{
                if(find_set(x) == find_set(y)){
                    printf("YES\n");
                }
                else{
                    printf("NO\n");
                }
            }
        }
    }
    return 0;
}