BZOJ3282 Tree

题目链接:戳我
算是LCT的板子题了吧qwq
大家不会LCT的可以去看flush_hu dalao的博客,也可以去看attack dalao的博客,都写得超级好呢qwqwq
不过大家要注意findroot那一点需要push_down一下啊qwq,要不然可能说不准哪个题就会挂掉qwqwq
代码如下:

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdio>
#define MAXN 300010
#define ls (t[x].ch[0])
#define rs (t[x].ch[1])
using namespace std;
int n,m;
int s[MAXN],top;
struct Node{int rev,v,s,ch[2],ff;}t[MAXN];
inline bool isroot(int x){return t[t[x].ff].ch[0]!=x&&t[t[x].ff].ch[1]!=x;}
inline void push_up(int x){t[x].s=t[ls].s^t[rs].s^t[x].v;}
inline void rotate(int x)
{
    int y=t[x].ff,z=t[y].ff;
    int k=t[y].ch[1]==x;
    if(!isroot(y)) t[z].ch[t[z].ch[1]==y]=x;t[x].ff=z;
    t[y].ch[k]=t[x].ch[k^1]; t[t[x].ch[k^1]].ff=y;
    t[x].ch[k^1]=y;t[y].ff=x;
    push_up(y),push_up(x);
}
inline void push_down(int x)
{
    if(!t[x].rev) return;
    t[x].rev^=1;swap(ls,rs);
    if(ls) t[ls].rev^=1;
    if(rs) t[rs].rev^=1;
}
inline void splay(int x)
{
    s[top=1]=x;
    for(int i=x;!isroot(i);i=t[i].ff) s[++top]=t[i].ff;
    while(top) push_down(s[top--]);
    while(!isroot(x))
    {
        int y=t[x].ff,z=t[y].ff;
        if(!isroot(y))
            ((t[y].ch[0]==x)^(t[z].ch[0]==y))?rotate(x):rotate(y);
        rotate(x);
    }
}
inline void access(int x)
    {for(int y=0;x;y=x,x=t[x].ff)splay(x),rs=y,push_up(x);}
inline void makeroot(int x)
    {access(x);splay(x);t[x].rev^=1;}
inline void split(int x,int y)
    {makeroot(x);access(y);splay(y);}
inline void link(int x,int y){makeroot(x);t[x].ff=y;}
inline void cut(int x,int y)
{
    split(x,y);
    if(t[y].ch[0]==x)
        t[y].ch[0]=t[x].ff=0;
}
inline int findroot(int x)
{
    access(x);
    splay(x);
    while(ls) push_down(x=ls);
    return x;
}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("ce.in","r",stdin);
    #endif
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++) scanf("%d",&t[i].v);
    int op,x,y;
    while(m--)
    {
        scanf("%d%d%d",&op,&x,&y);
        if(op==0) {split(x,y);printf("%d
",t[y].s);}
        if(op==1) {if(findroot(x)!=findroot(y))link(x,y);}
        else if(op==2) cut(x,y);
        else if(op==3) makeroot(x),t[x].v=y,push_up(x);
    }
    return 0;
}

原文地址:https://www.cnblogs.com/fengxunling/p/10284474.html