bzoj3282 Tree

lct不保证联通查父亲!

lct不保证联通查父亲!

lct不保证联通查父亲!

(重要的事情说三遍)

代码:

#include<cstdio>
#include<algorithm>
using namespace std;
#define N 300050
int n,m;
int ch[N][2],fa[N],v[N],s[N];
bool res[N],rt[N];
void update(int x)
{
    s[x] = s[ch[x][0]] ^ s[ch[x][1]] ^ v[x];
}
void reserve(int x)
{
    res[x]^=1;
    swap(ch[x][0],ch[x][1]);
}
void pushdown(int x)
{
    if(res[x])
    {
        res[x] = 0;
        reserve(ch[x][0]);
        reserve(ch[x][1]);
    }
}
void down(int x)
{
    if(!rt[x])down(fa[x]);
    pushdown(x);
}
void rotate(int x)
{
    int y = fa[x] , z = fa[y] , k = (ch[y][1]==x);
    if(rt[y])rt[y] = 0,rt[x] = 1;
    else ch[z][ch[z][1]==y] = x;
    fa[x] = z;
    ch[y][k] = ch[x][!k],fa[ch[x][!k]] = y;
    ch[x][!k] = y,fa[y] = x;
    update(y),update(x);
}
void splay(int x)
{
    down(x);
    while(!rt[x])
    {
        int y = fa[x] , z = fa[y];
        if(!rt[y])
            ((ch[y][1]==x)^(ch[z][1]==y))?rotate(x):rotate(y);
        rotate(x);
    }
}
void access(int x)
{
    int y =0;
    while(x)
    {
        splay(x);
        rt[ch[x][1]] = 1;
        rt[y] = 0;
        ch[x][1] = y;
        update(x);
        y = x,x = fa[x];
    }
}
void mtr(int x)
{
    access(x);
    splay(x);
    reserve(x);
}
int findfa(int x)
{
    access(x);
    splay(x);
    while(ch[x][0])x=ch[x][0];
    return x;
}
void link(int x,int y)
{
    mtr(x);
    fa[x] = y;
}
void cut(int x,int y)
{
    mtr(x);
    access(y);
    splay(y);
    if(ch[y][0]==x)
    {
        ch[y][0] = fa[x] = 0;
        rt[x] = 1;
    }
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&v[i]);
        s[i] = v[i];
        rt[i] = 1;
    }
    for(int op,x,y,i=1;i<=m;i++)
    {
        scanf("%d%d%d",&op,&x,&y);
        if(op==0)
        {
            mtr(x);
            access(y);
            splay(y);
            printf("%d\n",s[y]);
        }else if(op==1)
        {
            if(findfa(x)!=findfa(y))link(x,y);
        }else if(op==2)
        {
            if(findfa(x)==findfa(y))cut(x,y);
        }else
        {
            access(x);
            splay(x);
            v[x] = y;
            update(x);
        }
    }
    return 0;
}

 

posted @ 2018-09-13 10:11  LiGuanlin  阅读(109)  评论(0编辑  收藏  举报