BZOJ3223[Tyvj 1729 文艺平衡树]题解--splay

来源:互联网 发布:淘宝入驻 编辑:程序博客网 时间:2024/05/14 12:57

【链接】
bzoj3223

【题目大意】
给你一个序列,让你翻转区间。

【解题报告】
splay区间旋转模板题。

#include<cstdio>#include<algorithm>using namespace std;const int maxn=100005;int n,m;struct Splay{    Splay *son[2];    int x,s;    bool flip;    int Cmp(int &k) {if (k==son[0]->s+1) return -1; if (k<son[0]->s+1) return 0; k-=son[0]->s+1; return 1;}    void Pushup() {s=son[0]->s+son[1]->s+1;}}tem[maxn],*Null=tem,*len=Null,*ro=Null;inline int Read(){    int res=0;    char ch=getchar();    while (ch<'0'||ch>'9') ch=getchar();    while (ch>='0'&&ch<='9') res=res*10+ch-48,ch=getchar();    return res;}void Pushdown(Splay* k){    if (k->flip)    {        swap(k->son[0],k->son[1]); k->flip=0;        if (k->son[0]!=Null) k->son[0]->flip^=1;        if (k->son[1]!=Null) k->son[1]->flip^=1;    }}void New(Splay* &k,int x){    k=++len; k->x=x; k->s=1; k->flip=0; k->son[0]=k->son[1]=Null;}Splay* Build(int L,int R){    if (L>R) return Null;    int mid=(R-L>>1)+L;    Splay* now; New(now,mid);    now->son[0]=Build(L,mid-1); now->son[1]=Build(mid+1,R);    now->Pushup();    return now;}void Rotate(Splay* &k,int d){    Splay* t=k->son[d]; k->son[d]=t->son[d^1]; t->son[d^1]=k;    k->Pushup(); t->Pushup(); k=t;}void Splay_Work(Splay* &k,int x){    Pushdown(k);    int d1=k->Cmp(x);    if (d1>-1)    {        Splay* p=k->son[d1]; Pushdown(p);        int d2=p->Cmp(x);        if (d2>-1)        {            Splay_Work(p->son[d2],x);            if (d1==d2) Rotate(k,d1),Rotate(k,d1); else Rotate(k->son[d1],d2),Rotate(k,d1);        } else Rotate(k,d1);    }}void GetLR(Splay* &k,int L,int R){    L--; R++;    Splay_Work(k,L);    k->Cmp(R); Splay_Work(k->son[1],R);} void Write(Splay* k){    if (k==Null) return;    Pushdown(k); Write(k->son[0]); printf("%d ",k->x); Write(k->son[1]);}int main(){    freopen("3223.in","r",stdin);    freopen("3223.out","w",stdout);    n=Read(); m=Read();    ro=Build(0,n+1);    for (int i=1; i<=m; i++)    {        int L=Read()+1,R=Read()+1;        GetLR(ro,L,R); ro->son[1]->son[0]->flip^=1;    }    GetLR(ro,2,n+1); Write(ro->son[1]->son[0]);    return 0;}