UVA 11922 Splay tree

UVA 11922

题意:

有n个数1~n

操作a,b表示取出第a~b个数,翻转后添加到数列的尾部

输入n,m

输入m条指令a,b

输出最终的序列

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define Key_Value ch[ch[root][1]][0]
const int maxn=100009;
int n,m;
int pre[maxn],rev[maxn],key[maxn],size[maxn],ch[maxn][2],root,tot1;
void Update_Rev(int r){
    if(r==0) return;
    swap(ch[r][0],ch[r][1]);
    rev[r]^=1;
}
void Push_Down(int r){
    if(rev[r]){
        Update_Rev(ch[r][0]);
        Update_Rev(ch[r][1]);
        rev[r]=0;
    }
}
void Push_Up(int r){
    size[r]=1+size[ch[r][0]]+size[ch[r][1]];
}
void New_Node(int &r,int fa,int k){
    r=++tot1;
    pre[r]=fa;
    key[r]=k;
    rev[r]=ch[r][1]=ch[r][0]=0;
    size[r]=1;
}
void Build(int &x,int l,int r,int fa){
    if(l>r) return;
    int mid=(l+r)>>1;
    New_Node(x,fa,mid);
    Build(ch[x][0],l,mid-1,x);
    Build(ch[x][1],mid+1,r,x);
    Push_Up(x);
}
void Init(){
    root=tot1=0;
    pre[root]=rev[root]=key[root]=size[root]=ch[root][0]=ch[root][1]=0;
    New_Node(root,0,-1);
    New_Node(ch[root][1],root,-1);
    Build(Key_Value,1,n,ch[root][1]);
    Push_Up(ch[root][1]);
    Push_Up(root);
}
void Rotate(int x,int kind){
    int y=pre[x];
    Push_Down(y);
    Push_Down(x);
    ch[y][!kind]=ch[x][kind];
    pre[ch[x][kind]]=y;
    if(pre[y]) ch[pre[y]][ch[pre[y]][1]==y]=x;
    pre[x]=pre[y];
    ch[x][kind]=y;
    pre[y]=x;
    Push_Up(y);
}
void Splay(int r,int goal){
    while(pre[r]!=goal){
        if(pre[pre[r]]==goal)
            Rotate(r,ch[pre[r]][0]==r);
        else{
            int y=pre[r];
            int kind=ch[pre[y]][0]==y;
            if(ch[y][kind]==r){
                Rotate(r,!kind);
                Rotate(r,kind);
            }else{
                Rotate(y,kind);
                Rotate(r,kind);
            }
        }
    }
    Push_Up(r);
    if(goal==0) root=r;
}
int Get_Kth(int r,int k){
    Push_Down(r);
    int t=size[ch[r][0]];
    if(k==t+1) return r;
    else if(k<=t) return Get_Kth(ch[r][0],k);
    else return Get_Kth(ch[r][1],k-t-1);
}
void Solve(int a,int b){
    Splay(Get_Kth(root,a),0);
    Splay(Get_Kth(root,b+2),root);
    Update_Rev(Key_Value);
    Push_Up(ch[root][1]);
    Push_Up(root);
    int temp=Key_Value;
    Key_Value=0;

    Push_Up(ch[root][1]);
    Push_Up(root);       //更改了Key_Value要pushup
    Splay(Get_Kth(root,size[root]-1),0);
    Splay(Get_Kth(root,size[root]),root);
    Key_Value=temp;
    pre[Key_Value]=ch[root][1];
    Push_Up(ch[root][1]);
    Push_Up(root);
}
int cnt;
void print(int r){
    if(r==0) return;
    Push_Down(r);
    print(ch[r][0]);
    if(cnt<n&&key[r]>0){
        cnt++;
        printf("%d
",key[r]);
    }
    print(ch[r][1]);
}
int main()
{
    scanf("%d%d",&n,&m);
    Init();
    int x,y;
    while(m--){
        scanf("%d%d",&x,&y);
        Solve(x,y);
    }
    cnt=0;
    print(root);
    return 0;
}
原文地址:https://www.cnblogs.com/--ZHIYUAN/p/7147084.html