BZOJ 1180: [CROATIAN2009]OTOCI|动态树

做了几道LCT的题后发现终于会打裸题啦QAQ

#include<cstdio> 
#include<cstdlib> 
#include<cstring> 
#include<cmath> 
#include<queue> 
#include<set> 
#include<map> 
#include<vector> 
#include<algorithm> 
#include<iostream> 
#define N 303333 
using namespace std;  
int sc()  
{  
    int i=0,f=1; char c=getchar();  
    while(c>'9'||c<'0'){if(c=='-')f=-1; c=getchar();}  
    while(c>='0'&&c<='9') i=i*10+c-'0',c=getchar();  
    return i*f;  
}  
bool rev[N];
int v[N],val[N],fa[N],ch[N][2],st[N];
int n,m;
bool Root(int x){return ch[fa[x]][0]!=x&&ch[fa[x]][1]!=x;}
void push_up(int x)
{
    val[x]=val[ch[x][0]]+val[ch[x][1]]+v[x];
}
void push_down(int x)
{
    if(rev[x])
    {
        rev[ch[x][0]]^=1;rev[ch[x][1]]^=1;
        swap(ch[x][1],ch[x][0]);rev[x]=0;
    }
}
void rotate(int x)
{
    int y=fa[x],z=fa[y],l,r;
    l=(ch[y][1]==x);r=l^1;
    if(!Root(y))ch[z][ch[z][1]==y]=x;
    fa[x]=z;fa[y]=x;fa[ch[x][r]]=y;
    ch[y][l]=ch[x][r];ch[x][r]=y;
    push_up(y),push_up(x);
}
void splay(int x)
{
    int top=1;st[1]=x;
    for(int i=x;!Root(i);i=fa[i])st[++top]=fa[i];
    while(top)push_down(st[top--]);
    while(!Root(x))
    {
        int y=fa[x],z=fa[y];
        if(!Root(y))
            if(ch[z][0]==y^ch[y][0]==x)rotate(x);
            else rotate(y);
        rotate(x);
    }
}
void access(int x)
{
    for(int t=0;x;t=x,x=fa[x])
        splay(x),ch[x][1]=t,push_up(x);
}
void make_root(int x)
{
    access(x),splay(x),rev[x]^=1;
}
void link(int x,int y)
{
    make_root(x),fa[x]=y;
}
void cut(int x,int y)
{
    make_root(x),access(y),splay(y);
    fa[x]=ch[y][0]=0,push_up(y);
}
int find(int x)
{
    access(x),splay(x);
    while(ch[x][0])x=ch[x][0],push_down(x);
    return x;
}
int main()
{
    n=sc();
    for(int i=1;i<=n;i++)v[i]=val[i]=sc();
    m=sc();
    while(m--)
    {
        char s[11]; scanf("%s",s);
        if(s[0]=='b')
        {
            int x=sc(),y=sc();
            if(find(x)!=find(y))
            {
                puts("yes");
                link(x,y);
            }
            else puts("no");
        }
        else if(s[0]=='p')
        {
            int x=sc(),y=sc();
            make_root(x),v[x]=y;
            push_up(x);
        }
        else if(s[0]=='e')
        {
            int x=sc(),y=sc();
            int fx=find(x),fy=find(y);
            if(fx==fy)
            {
                make_root(x);
                access(y);
                splay(y);
                printf("%d\n",val[y]);
            }
            else puts("impossible");
        }
    }
    return 0;
}

你可能感兴趣的:(动态树)