UVA11922 Permutation Transformer

思路

直接使用FHQ Treap维护即可

代码

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct Node{
    int lson,rson,val,ran,sz,inv;
}FHQ[100100];
int Nodecnt=0,a[100100],n,m,root;
void pushup(int o){
    FHQ[o].sz=FHQ[FHQ[o].lson].sz+FHQ[FHQ[o].rson].sz+1;
}
void pushdown(int o){
    if(FHQ[o].inv){
        FHQ[FHQ[o].lson].inv^=1;
        FHQ[FHQ[o].rson].inv^=1;
        swap(FHQ[o].lson,FHQ[o].rson);
        FHQ[o].inv=0; 
    }
}
int build(int l,int r){
    if(l>r)
        return 0;
    int o=++Nodecnt;
    FHQ[o].inv=FHQ[o].lson=FHQ[o].rson=0;
    int mid=(l+r)>>1;
    FHQ[o].ran=rand();
    FHQ[o].sz=1;
    FHQ[o].val=a[mid];
    FHQ[o].lson=build(l,mid-1);
    FHQ[o].rson=build(mid+1,r);
    pushup(o);
    return o;
}
void split(int now,int val,int &x,int &y){
    if(!now){
        x=y=0;
        return;
    }
    pushdown(now);
    if(FHQ[FHQ[now].lson].sz>=val){
        y=now;
        split(FHQ[now].lson,val,x,FHQ[now].lson);
        pushup(now);
    }
    else{
        x=now;
        split(FHQ[now].rson,val-FHQ[FHQ[now].lson].sz-1,FHQ[now].rson,y);
        pushup(now);
    }
}
int merge(int x,int y){
    if(x*y==0)
        return x+y;
    pushdown(x);
    pushdown(y);
    if(FHQ[x].ran<FHQ[y].ran){
        FHQ[x].rson=merge(FHQ[x].rson,y);
        pushup(x);
        return x;
    }
    else{
        FHQ[y].lson=merge(x,FHQ[y].lson);
        pushup(y);
        return y;
    }
}
void output(int o){
    if(!o)
        return;
    pushdown(o);
    output(FHQ[o].lson);
    printf("%d\n",FHQ[o].val);
    output(FHQ[o].rson);
}
int main(){
    // freopen("test.in","r",stdin);
    // freopen("test.out","w",stdout);
    scanf("%d %d",&n,&m);
    for(int i=1;i<=n;i++)
        a[i]=i;
    root=build(1,n);
    for(int i=1;i<=m;i++){
        int l,r;
        scanf("%d %d",&l,&r);
        int lroot,midroot,tmproot,rroot;
        split(root,l-1,lroot,tmproot);
        split(tmproot,r-l+1,midroot,rroot);
        FHQ[midroot].inv^=1;
        pushdown(midroot);
        root=merge(merge(lroot,rroot),midroot);
    }
    output(root);
    return 0;
}

posted @ 2019-04-15 17:28  dreagonm  阅读(113)  评论(0编辑  收藏  举报