【BZOJ】3674: 可持久化并查集加强版

题解

感觉全世界都写过只有我没写过

毕竟是板子还是挺简单的,只要用可持久化线段树维护一下数组的形态就好了,每个数组里面维护这个数组的father,和这个点所在树的最长链的深度(如果这个点是根按秩合并要用)

为了避免返回两个值可以直接返回所在线段树节点的编号

代码

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <set>
#include <cmath>
#include <bitset>
#define enter putchar('\n')
#define space putchar(' ')
//#define ivorysi
#define pb push_back
#define mo 974711
#define pii pair<int,int>
#define mp make_pair
#define fi first
#define se second
#define MAXN 200005
using namespace std;
typedef long long int64;
typedef double db;
template<class T>
void read(T &res) {
    res = 0;char c = getchar();T f = 1;
    while(c < '0' || c > '9') {
	if(c == '-') f = -1;
	c = getchar();
    }
    while(c >= '0' && c <= '9') {
	res = res * 10 - '0' + c;
	c = getchar();
    }
    res = res * f;
}
template<class T>
void out(T x) {
    if(x < 0) {x = -x;putchar('-');}
    if(x >= 10) out(x / 10);
    putchar('0' + x % 10);
}

int N,M;
struct node {
    int f,dep,lc,rc;
}tr[MAXN * 80];
int rt[MAXN],Ncnt;
void build(int &u,int l,int r) {
    u = ++Ncnt;
    if(l == r) {
	tr[u].f = l;
	tr[u].dep = 1;
	return;
    }
    int mid = (l + r) >> 1;
    build(tr[u].lc,l,mid);
    build(tr[u].rc,mid + 1,r);
}
int Query(int u,int L,int R,int pos) {
    if(L == R) return u;
    int mid = (L + R) >> 1;
    if(pos <= mid) return Query(tr[u].lc,L,mid,pos);
    else return Query(tr[u].rc,mid + 1,R,pos);
}
void Change(int x,int &y,int L,int R,int pos,int v) {
    y = ++Ncnt;
    tr[y] = tr[x];
    if(L == R) {tr[y].f = v;return;}
    int mid = (L + R) >> 1;
    if(pos <= mid) Change(tr[x].lc,tr[y].lc,L,mid,pos,v);
    else Change(tr[x].rc,tr[y].rc,mid + 1,R,pos,v);
}
void Inc_dep(int x,int &y,int L,int R,int pos) {
    y = ++Ncnt;
    tr[y] = tr[x];
    if(L == R) {tr[y].dep++;return;}
    int mid = (L + R) >> 1;
    if(pos <= mid) Inc_dep(tr[x].lc,tr[y].lc,L,mid,pos);
    else Inc_dep(tr[x].rc,tr[y].rc,mid + 1,R,pos);
}
int getfa(int u,int x) {
    int p = Query(u,1,N,x);
    if(tr[p].f == x) return p;
    else return getfa(u,tr[p].f);
}
void Solve() {
    read(N);read(M);
    build(rt[0],1,N);
    int op,a,b;
    for(int i = 1 ; i <= M ; ++i) {
	read(op);
	if(op == 1) {
	    rt[i] = rt[i - 1];
	    read(a);read(b);
	    a = getfa(rt[i],a);b = getfa(rt[i],b);
	    if(a == b) continue;
	    if(tr[a].dep < tr[b].dep) Change(rt[i],rt[i],1,N,tr[a].f,tr[b].f);
	    else if(tr[b].dep < tr[a].dep) Change(rt[i],rt[i],1,N,tr[b].f,tr[a].f);
	    else {
		Change(rt[i],rt[i],1,N,tr[a].f,tr[b].f);
		Inc_dep(rt[i],rt[i],1,N,tr[b].f);
	    }
	}
	else if(op == 2) {
	    read(a);
	    rt[i] = rt[a];
	}
	else if(op == 3) {
	    rt[i] = rt[i - 1];
	    read(a);read(b);
	    a = getfa(rt[i],a);b = getfa(rt[i],b);
	    if(a == b) {puts("1");}
	    else puts("0");
	}
    }
}
int main() {
#ifdef ivorysi
    freopen("f1.in","r",stdin);
#endif
    Solve();
}
posted @ 2018-06-19 15:53  sigongzi  阅读(156)  评论(0编辑  收藏  举报