题意:
3种操作
1 a b 合并a,b所在集合
2 k 回到第k次操作之后的状态(查询算作操作)
3 a b 询问a,b是否属于同一集合,是则输出1否则输出0
做法:
可持久化并查集,相当于每个时间建一棵线段树维护每个数的fa[]。
代码:
/*************************************************************
Problem: bzoj 3673 可持久化并查集 by zky
User: fengyuan
Language: C++
Result: Accepted
Time: 96 ms
Memory: 6056 kb
Submit_Time: 2017-12-29 12:22:03
*************************************************************/
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#define mid ((l+r)/2)
using namespace std;
const int N = 20010, M = 400010;
int n, m, tot, now;
int fa[M], T[N], R[M], L[M];
inline void build(int &rt, int l, int r)
{
rt = ++ tot; if(l == r) { fa[rt] = l; return; }
build(L[rt], l, mid); build(R[rt], mid+1, r);
}
inline int query(int rt, int l, int r, int x)
{
if(l == r) return rt;
if(x <= mid) return query(L[rt], l, mid, x);
else return query(R[rt], mid+1, r, x);
}
inline int getFa(int rt, int x)
{
int p = query(rt, 1, n, x);
if(x == fa[p]) return p; else return getFa(rt, fa[p]);
}
inline void modify(int pre, int &rt, int l, int r, int x, int y)
{
rt = ++ tot;
if(l == r) { fa[rt] = y; return; }
L[rt] = L[pre]; R[rt] = R[pre];
if(x <= mid) modify(L[pre], L[rt], l, mid, x, y);
else modify(R[pre], R[rt], mid+1, r, x, y);
}
inline void merge(int x, int y)
{
modify(T[now-1], T[now], 1, n, fa[x], fa[y]);
}
inline void work(int x, int y)
{
int fx = getFa(T[now], x), fy = getFa(T[now], y);
if(fa[fx] != fa[fy]) merge(fx, fy);
}
inline bool qry(int x, int y)
{
int fx = getFa(T[now], x), fy = getFa(T[now], y);
return fa[fx] == fa[fy];
}
int main()//可持久化并查集,相当于每个时间建一棵线段树维护每个数的fa[]
{
scanf("%d%d", &n, &m);
build(T[0], 1, n);
for(int i = 1; i <= m; i ++) {
int opt, x, y; scanf("%d%d", &opt, &x);
if(opt == 2) { T[i] = T[x]; continue; }
now = i;
T[i] = T[i-1]; scanf("%d", &y);
if(opt == 1) work(x, y);
else printf("%d\n", qry(x, y));
}
return 0;
}