洛谷 P3402 [模板]可持久化并查集
题面
解法
用可持久化线段树维护每一个点的父亲,不能路径压缩
直接暴力一步一步跳即可
注意要启发式合并
时间复杂度:\(O(q\ log^2\ n)\)
代码
#include <bits/stdc++.h>
#define PI pair <int, int>
#define mp make_pair
#define N 200010
using namespace std;
template <typename node> void read(node &x) {
x = 0; int f = 1; char c = getchar();
while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); x *= f;
}
struct Node {
int lc, rc, val, siz;
} t[N * 30];
int n, q, tot, rt[N];
void build(int &k, int l, int r) {
k = ++tot;
if (l == r) {
t[k].val = l, t[k].siz = 1;
return;
}
int mid = (l + r) >> 1;
build(t[k].lc, l, mid), build(t[k].rc, mid + 1, r);
}
void ins(int &k, int cur, int l, int r, int x, int f, int siz) {
k = ++tot; t[k] = t[cur];
if (l == r) {
t[k].val = f, t[k].siz = siz;
return;
}
int mid = (l + r) >> 1;
if (x <= mid) ins(t[k].lc, t[cur].lc, l, mid, x, f, siz);
else ins(t[k].rc, t[cur].rc, mid + 1, r, x, f, siz);
}
PI query(int k, int l, int r, int x) {
if (l == r) return mp(t[k].val, t[k].siz);
int mid = (l + r) >> 1;
if (x <= mid) return query(t[k].lc, l, mid, x);
return query(t[k].rc, mid + 1, r, x);
}
int Find(int now, int x) {
int fa = x;
while (true) {
PI tmp = query(rt[now], 1, n, fa);
if (tmp.first == fa) return fa;
fa = tmp.first;
}
}
void merge(int t, int x, int y) {
int tx = Find(t - 1, x), ty = Find(t - 1, y); rt[t] = rt[t - 1];
if (tx == ty) return;
PI a = query(rt[t], 1, n, tx), b = query(rt[t], 1, n, ty);
int siza = a.second, sizb = b.second;
if (siza > sizb) swap(tx, ty), swap(siza, sizb);
ins(rt[t], rt[t], 1, n, tx, ty, siza);
ins(rt[t], rt[t], 1, n, ty, ty, siza + sizb);
}
int main() {
read(n), read(q);
build(rt[0], 1, n);
for (int t = 1; t <= q; t++) {
int opt; read(opt);
if (opt == 1) {
int x, y; read(x), read(y);
merge(t, x, y);
}
if (opt == 2) {
int k; read(k);
rt[t] = rt[k];
}
if (opt == 3) {
int x, y; read(x), read(y);
rt[t] = rt[t - 1];
int tx = Find(t, x), ty = Find(t, y);
if (tx == ty) cout << "1\n"; else cout << "0\n";
}
}
return 0;
}