[BZOJ1180][CROATIAN2009]OTOCI(LCT)

题目描述

传送门

题解

和极地旅行社一样。可是CROATIAN是smg

代码

#include
#include
#include
using namespace std;

const int max_n=3e4+5;

int n,m,A,B,X;
char opt[20];
int a[max_n];
int f[max_n],ch[max_n][2],sum[max_n],reverse[max_n];
int strack[max_n];

inline int get(int x){
    return ch[ f[x] ][1]==x;
}

inline int Is_Root(int x){
    return ch[ f[x] ][0]!=x&&ch[ f[x] ][1]!=x;
}

inline void update(int x){
    sum[x]=a[x];
    if (ch[x][0]) sum[x]+=sum[ ch[x][0] ];
    if (ch[x][1]) sum[x]+=sum[ ch[x][1] ];
}

inline void pushdown(int x){
    if (x&&reverse[x]){
        swap(ch[x][0],ch[x][1]);
        if (ch[x][0]) reverse[ ch[x][0] ]^=1;
        if (ch[x][1]) reverse[ ch[x][1] ]^=1;
        reverse[x]=0;
    }
}

inline void rotate(int x){
    int old=f[x],oldf=f[old],which=get(x);

    if (!Is_Root(old))
      ch[oldf][ ch[oldf][1]==old ]=x;
    f[x]=oldf;

    ch[old][which]=ch[x][which^1];
    f[ ch[old][which] ]=old;

    ch[x][which^1]=old;
    f[old]=x;

    update(old);
    update(x);
}

inline void splay(int x){
    int temp=0;
    strack[++temp]=x;
    for (int i=x; !Is_Root(i); i=f[i])
      strack[++temp]=f[i];
    for (int i=temp; i>=1; --i) pushdown(strack[i]);

    for (int fa; !Is_Root(x); rotate(x))
      if (!Is_Root(fa=f[x]))
        rotate( (get(x)==get(fa)) ?fa:x );
}

inline void Access(int x){
    int t=0;
    for (; x; t=x,x=f[x]){
        splay(x);
        ch[x][1]=t;
        update(x);//
    }
}

inline void Reverse(int x){
    Access(x);
    splay(x);
    reverse[x]^=1;
}

inline int find(int x){
    Access(x);
    splay(x);
    while (ch[x][0])
      x=ch[x][0];
    return x;
}

inline void Link(int x,int y){
    Reverse(x);
    f[x]=y;
    splay(x);
}

int main(){
//  freopen("input.txt","r",stdin);
    scanf("%d",&n);
    for (int i=1;i<=n;++i){
        scanf("%d",&a[i]);
        sum[i]=a[i];
    }

    scanf("%d",&m);
    for (int i=1;i<=m;++i){
        scanf("%s",opt);
        if (opt[0]=='b'){
            scanf("%d%d",&A,&B);
            if (find(A)==find(B))
              printf("no\n");
            else{
                printf("yes\n");
                Link(A,B);
            }
        }
        if (opt[0]=='p'){
            scanf("%d%d",&A,&X);
            a[A]=X;
            Access(A);
            splay(A);//
        }
        if (opt[0]=='e'){
            scanf("%d%d",&A,&B);
            if (find(A)==find(B)){
                Reverse(A);
                Access(B);
                splay(B);
                int ans=sum[B];
                printf("%d\n",ans);
            }
            else
              printf("impossible\n");
        }
    }
}

你可能感兴趣的:(题解,lct)