[BZOJ1552][Cerc2007]robotic sort(splay)

题目描述

传送门

题解

splay模板题。

代码

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;

const int max_n=1e5+5;
const int INF=1e9;

int n,root,sz;
int rank[max_n],num[max_n],f[max_n],ch[max_n][2],size[max_n],delta[max_n];
struct hp{int val,id;}a[max_n];

inline int cmp(hp a,hp b){return a.val<b.val||(a.val==b.val&&a.id<b.id);}
inline int get(int x){
    return x==ch[f[x]][1];
}
inline void update(int x){
    if (x){
        size[x]=1;
        if (ch[x][0]) size[x]+=size[ch[x][0]];
        if (ch[x][1]) size[x]+=size[ch[x][1]];
    }
}
inline void pushdown(int x){
    if (x&&delta[x]){
        swap(ch[x][0],ch[x][1]);
        if (ch[x][0]) delta[ch[x][0]]^=1;
        if (ch[x][1]) delta[ch[x][1]]^=1;
        delta[x]=0;
    }
}
inline void rotate(int x){
    pushdown(f[x]);
    pushdown(x);
    int old=f[x],oldf=f[old],which=get(x);
    ch[old][which]=ch[x][which^1];
    f[ch[old][which]]=old;
    ch[x][which^1]=old;
    f[old]=x;
    if (oldf) ch[oldf][ch[oldf][1]==old]=x;
    f[x]=oldf;
    update(old);
    update(x);
}
inline void splay(int x,int tar){
    for (int fa;(fa=f[x])!=tar;rotate(x))
      if (f[fa]!=tar)
        rotate((get(x)==get(fa))?fa:x);
    if (!tar) root=x;
}
inline int build(int l,int r,int fa){
    if (l>r) return 0;
    int mid=(l+r)>>1;
    int now=++sz;
    num[rank[mid]]=sz; f[now]=fa; delta[now]=0;
    int lch=build(l,mid-1,now);
    int rch=build(mid+1,r,now);
    ch[now][0]=lch; ch[now][1]=rch;
    update(now);
    return now;
} 
inline int find(int x){
    int now=root;
    while (1){
        pushdown(now);
        if (ch[now][0]&&size[ch[now][0]]>=x) now=ch[now][0];
        else{
            int temp=1;
            if (ch[now][0]) temp+=size[ch[now][0]];
            if (x<=temp) return now;
            x-=temp; now=ch[now][1];
        }
    }
}
int main(){
    scanf("%d",&n);
    for (int i=1;i<=n;++i) scanf("%d",&a[i].val),a[i].id=i;
    sort(a+1,a+n+1,cmp);
    for (int i=1;i<=n;++i) rank[a[i].id+1]=i;
    root=build(1,n+2,0);
    for (int i=1;i<=n;++i){
        int number=num[i];
        splay(number,0);
        int ans=size[ch[root][0]];
        printf("%d%c",ans," \n"[i==n]);
        if (i==n) break;
        //i-1 ans+1 
        int a=i; int b=ans+2;
        if (a>b) swap(a,b);
        int aa=find(a);
        int bb=find(b);
        splay(aa,0);
        splay(bb,aa);
        delta[ch[ch[root][1]][0]]^=1;
    }
}

你可能感兴趣的:(splay,bzoj)