CodeForces - 566D Restructuring Company——并查集

#include 
using namespace std;
const int maxn = 200000 + 10;
int n, q, par[maxn], next[maxn];
int seek(int x) { return par[x] == x ? x : par[x] = seek(par[x]); }
int main() {
    scanf("%d %d", &n, &q);
    for (int i = 0; i <= n; i++) par[i] = i, next[i] = i + 1;
    while (q--) {
        int op, x, y;
        scanf("%d %d %d", &op, &x, &y);
        if (op == 1) par[seek(x)] = seek(y);
        else if (op == 2) {
            while (x < y) {
                par[seek(x)] = seek(y);
                int t = next[x]; next[x] = next[y]; x = t;
            }
        }
        else {
            puts(seek(x) == seek(y) ? "YES" : "NO");
        }
    }
}

你可能感兴趣的:(数据结构)