[CODEVS1743]反转卡片(splay)

题目描述

传送门

题解

splay模板题。

代码

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

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

int n,root,sz,cnt;
int a[max_n],f[max_n],ch[max_n][2],size[max_n],key[max_n],delta[max_n];
bool flag;

inline int get(int x)
{
    return ch[f[x]][1]==x;
}
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 int build(int l,int r,int fa)
{
    int mid=(l+r)>>1;
    if (l>r) return 0;
    int now=++sz;
    key[now]=a[mid]; 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 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 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);
    a[1]=-INF; a[n+2]=INF;
    for (int i=1;i<=n;++i) scanf("%d",&a[i+1]);
    root=build(1,n+2,0);
    flag=false;
    while (cnt<100000)
    {
        int aa=find(2);
        int t;
        if ((t=key[aa])!=1)
        {
            cnt++;
            int aa=find(1);
            int bb=find(t+2);
            splay(aa,0);
            splay(bb,aa);
            delta[ch[ch[root][1]][0]]^=1;
        }
        else
        {
            flag=true;
            break;
        }
    }
    if (flag) printf("%d\n",cnt);
    else printf("-1\n");
}

总结

find不要忘了pushdown

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