bzoj 3282 Tree 动态树LCT

学了一天LCT,还是不太明白,打(抄)了一个模板,先存着。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<stack>
#define maxn 300005
using namespace std;
void read(int &a)
{
    a=0;char c=getchar();
    while(c<'0'||c>'9')
        c=getchar();
    while(c>='0'&&c<='9')
    {
        a*=10;a+=c-'0';
        c=getchar();
    }
}
int fa[maxn],ch[maxn][2];
int val[maxn],d[maxn];
bool rev[maxn];
void up(int x)
{val[x]=val[ch[x][0]]^val[ch[x][1]]^d[x];}
bool isroot(int x)
{return ch[fa[x]][0]!=x&&ch[fa[x]][1]!=x;}
void down(int x)
{
    if(rev[x])
    {
        rev[ch[x][0]]^=1;
        rev[ch[x][1]]^=1;
        swap(ch[x][0],ch[x][1]);
        rev[x]=0;
    }
}
bool dir(int x)
{return x==ch[fa[x]][1];}
void rotate(int x)
{
    int y=fa[x];
    int z=fa[y];
    bool b=dir(x);
    int a=ch[x][!b];
    if(!isroot(y)) 
        ch[z][dir(y)]=x;
    fa[x]=z;fa[y]=x;
    ch[x][!b]=y;
    ch[y][b]=a;
    if(a) fa[a]=y;
    up(y);up(x);
}
stack<int> S;
void splay(int x)
{
    S.push(x);
    for(int i=x;!isroot(i);i=fa[i])
        S.push(fa[i]);
    while(!S.empty())
    {
        int v=S.top();
        S.pop();down(v);
    }
    while(!isroot(x))
    {
        int y=fa[x];
        if(isroot(y))   rotate(x);
        else
        {
            bool b=dir(x),c=dir(y);
            if(b^c) {rotate(x);rotate(x);}
            else    {rotate(y);rotate(x);}
        }
    }
}
void access(int x)
{
    int t=0;
    while(x){
        splay(x);ch[x][1]=t;up(x);
        t=x;x=fa[x];
    }
}
void make_root(int x)
{access(x);splay(x);rev[x]^=1;}
void link(int u,int v)
{make_root(u);fa[u]=v;}
void cut(int x,int y)
{
    make_root(x);access(y);splay(y);
    if(ch[y][0]==x) ch[y][0]=fa[x]=0,up(y);
}
int find(int x)
{
    access(x);splay(x);
    while(ch[x][0]) x=ch[x][0];
    return x;
}
int main()
{
    int n,q;
    read(n);read(q);
    int op,x,y;
    for(int i=1;i<=n;i++)
        read(d[i]);
    for(int i=1;i<=q;i++)
    {
        read(op);read(x);read(y);
        if(op==0)
        {
            int ans=0;
            make_root(x);access(y);splay(y);
            printf("%d\n",val[y]);
        }
        if(op==1)
            if(find(x)!=find(y))link(x,y);
        if(op==2)
            if(find(x)==find(y))cut(x,y);
        if(op==3)
        {
            splay(x);d[x]=y;up(x);
        }
    }
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值