[BZOJ3282] Tree - LCT

Description

给定N个点以及每个点的权值,要你处理接下来的M个操作。
操作有4种。操作从0到3编号。点从1到N编号。
0:后接两个整数(x,y),代表询问从x到y的路径上的点的权值的xor和。
保证x到y是联通的。
1:后接两个整数(x,y),代表连接x到y,若x到Y已经联通则无需连接。
2:后接两个整数(x,y),代表删除边(x,y),不保证边(x,y)存在。
3:后接两个整数(x,y),代表将点X上的权值变成Y。

Solution

LCT 模板题

#include <bits/stdc++.h>
using namespace std;

const int N = 300005;

int n,m,val[N],t1,t2,t3;

namespace lct {
	int top, q[N], ch[N][2], fa[N], xr[N], rev[N];
	inline void pushup(int x){
		xr[x]=xr[ch[x][0]]^xr[ch[x][1]]^val[x];
	}
	inline void pushdown(int x){
		if(!rev[x]) return;
		rev[ch[x][0]]^=1;
		rev[ch[x][1]]^=1;
		rev[x]^=1;
		swap(ch[x][0],ch[x][1]);
	}
	inline bool isroot(int x){
		return ch[fa[x]][0]!=x && ch[fa[x]][1]!=x;
	}
	inline void rotate(int p){
		int q=fa[p], y=fa[q], x=ch[fa[p]][1]==p;
		ch[q][x]=ch[p][x^1]; fa[ch[q][x]]=q;
		ch[p][x^1]=q; fa[q]=p; fa[p]=y;
		if(y) if(ch[y][0]==q) ch[y][0]=p;
		else  if(ch[y][1]==q) ch[y][1]=p;
		pushup(q); pushup(p);
	}
	inline void splay(int x){
		q[top=1]=x;
		for(int i=x;!isroot(i);i=fa[i]) q[++top]=fa[i];
		for(int i=top;i;i--) pushdown(q[i]);
		for(;!isroot(x);rotate(x))
			if(!isroot(fa[x]))
				rotate((ch[fa[x]][0]==x)==(ch[fa[fa[x]]][0]==fa[x])?fa[x]:x);
	}
	void access(int x){
		for(int t=0;x;t=x,x=fa[x])
			splay(x),ch[x][1]=t,pushup(x);
	}
	void makeroot(int x){
		access(x);
		splay(x);
		rev[x]^=1;
	}
	int find(int x){
		access(x);
		splay(x);
		while(ch[x][0]) x=ch[x][0];
		return x;
	}
	void split(int x,int y){
		makeroot(x);
		access(y);
		splay(y);
	}
	void cut(int x,int y){
		split(x,y);
		if(ch[y][0]==x)
			ch[y][0]=0, fa[x]=0;
	}
	void link(int x,int y){
		makeroot(x);
		fa[x]=y;
	}
	int query(int x,int y) {
	    split(x,y);
	    return xr[y];
	}
}

int main(){
    ios::sync_with_stdio(false);
    cin>>n>>m;
    for(int i=1;i<=n;i++) {
        cin>>val[i];
    }
    for(int i=1;i<=m;i++) {
        int t1,t2,t3;
        cin>>t1>>t2>>t3;
        if(t1==0) {
            cout<<lct::query(t2,t3)<<endl;
        }
        if(t1==1) {
            lct::link(t2,t3);
        }
        if(t1==2) {
            lct::cut(t2,t3);
        }
        if(t1==3) {
            lct::split(t2,t2);
            val[t2]=t3;
            lct::pushup(t2);
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/mollnn/p/13164223.html