欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

bzoj 3673 可持久化并查集 by zky

程序员文章站 2024-03-02 20:14:58
...
n个集合 m个操作
操作:
1 a b 合并a,b所在集合

2 k 回到第k次操作之后的状态(查询算作操作)

3 a b 询问a,b是否属于同一集合,是则输出1否则输出0

0<n,m<=2*10^4


水题。把fa数组可持久化就好了。

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;

inline int read() {
	int x = 0, flag = 1; char ch = getchar();
	while (ch > '9' || ch < '0') { flag = ch == '-' ? -1 : 1; ch = getchar(); }
	while (ch <= '9' && ch >= '0') { x = x * 10 + ch - '0'; ch = getchar(); }
	return x * flag;
}

#define rep(ii, aa, bb) for (int ii = aa; ii <= bb; ii++)
#define N 1000001
#define getMid int mid = l + r >> 1

int n, m;
int root[N], ls[N], rs[N], v[N], sz; // the tree

void build(int &k, int l, int r) {
	if (!k) k = ++sz;
	if (l == r) {
		v[k] = l;
		return;
	}
	getMid;
	build(ls[k], l, mid);
	build(rs[k], mid + 1, r);
}

int query(int k, int l, int r, int pos) {
	if (l == r) return k;
	getMid;
	if (pos <= mid) return query(ls[k], l, mid, pos);
	else return query(rs[k], mid + 1, r, pos);
}

int getFa(int k, int x) {
	int p = query(k, 1, n, x);
	if (v[p] == x) return p;
	return getFa(k, v[p]);
}

void update(int l, int r, int x, int &y, int pos, int val) {
	y = ++sz;
	if (l == r) {
		v[y] = val;
		return;
	}
	ls[y] = ls[x];
	rs[y] = rs[x];
	getMid;
	if (pos <= mid) update(l, mid, ls[x], ls[y], pos, val);
	else update(mid + 1, r, rs[x], rs[y], pos, val);
}

int main() {
	n = read(), m = read();
	build(root[0], 1, n);
	rep(i, 1, m) {
		int op = read();
		int a = read(), b;
		if (op == 1) {
			b = read();
			root[i] = root[i - 1];
			int p = getFa(root[i], a), q = getFa(root[i], b);
			if (v[p] == v[q]) continue;
			update(1, n, root[i - 1], root[i], v[p], v[q]);
		}
		else if (op == 2) root[i] = root[a];
		else {
			b = read();
			root[i] = root[i - 1];
			int p = getFa(root[i], a), q = getFa(root[i], b);
			printf("%d\n", v[p] == v[q]);
		}
	}
	return 0;
}