BZOJ3223: Tyvj 1729 文艺平衡树 无旋Treap

一开始光知道pushdown却忘了pushup.........

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<queue>
#define MAXN 100010
using namespace std;
inline int read()
{
   int sum=0;
   char ch=getchar();
   while(ch<'0'||ch>'9')ch=getchar();
   while(ch>='0'&&ch<='9')
   {
      sum=(sum<<1)+(sum<<3)+ch-'0';
      ch=getchar();
   }
   return sum;
}
struct Treap
{
   struct Node
   {
       Node *ch[2];
       int size,v,key;
       bool rev;
       void pushup()
       {
          size=ch[0]->size+ch[1]->size+1;
       }
   }null[MAXN],*root,*q[MAXN];
   void swap(Node *&x,Node *&y)
   {
      Node *temp=x;
      x=y;
      y=temp;
   }
   void pushdown(Node *p)
   {
       if(!p->rev)return;
       p->ch[0]->rev^=1;
       p->ch[1]->rev^=1;
       swap(p->ch[0],p->ch[1]);
       p->rev=0;
   }
   int head,tail;
   int sz;
   Node *build(int l,int r)
   {
      if(l>r)return null;
      int mid=(l+r)>>1;
      null[mid].ch[0]=build(l,mid-1);
      null[mid].ch[1]=build(mid+1,r);
      null[mid].pushup();
      return &null[mid];
   }
   void bfs()
   {
      q[1]=root;
      head=tail=1;
      while(head<=tail)
      {
         Node *x=q[head++];
         x->v=++sz;
         if(x->ch[1]!=null)q[++tail]=x->ch[1];
         if(x->ch[0]!=null)q[++tail]=x->ch[0];
      }
   }
   void Init(int n)
   {
       null->ch[0]=null->ch[1]=null;
       for(int i=1;i<=n;i++)
        null[i].ch[0]=null[i].ch[1]=null,null[i].size=1,null[i].key=i;
       root=build(1,n);
       bfs();
   }
   Node *Merge(Node *a,Node *b)
   {
      if(a==null)return b;
      if(b==null)return a;
      if(a->v<b->v)
      {
          pushdown(a);
          a->ch[1]=Merge(a->ch[1],b);
          a->pushup();
          return a;
      }
      else
      {
          pushdown(b);
          b->ch[0]=Merge(a,b->ch[0]);
          b->pushup();
          return b;
      }
   }
   pair<Node*,Node*> split(Node *p,int k)
   {
      if(p==null)return make_pair(null,null);
      pushdown(p);
      if(p->ch[0]->size>=k)
      {
        pair<Node*,Node*> y=split(p->ch[0],k);
        p->ch[0]=y.second;
        p->pushup();
        y.second=p;
        return y;                        
      }
      pair<Node*,Node*> y=split(p->ch[1],k-p->ch[0]->size-1);
      p->ch[1]=y.first;
      p->pushup();
      y.first=p;
      return y;
   }
   void Rev(int l,int r)
   {
      pair<Node*,Node*> x=split(root,l-1);
      pair<Node*,Node*> y=split(x.second,r-l+1);
      y.first->rev^=1;
      root=Merge(Merge(x.first,y.first),y.second);
   }
   void Print(Node *p)
   {
      pushdown(p);
      if(p==null)return;
      Print(p->ch[0]);
      printf("%d ",p->key);
      Print(p->ch[1]);
   }
}YY;
int main()
{
   int n=read(),m=read();
   YY.Init(n);
   while(m--)
   {
      int l=read(),r=read();
      YY.Rev(l,r);
   } 
   YY.Print(YY.root);
   return 0;
}

 

posted @ 2017-07-12 15:26  TS_Hugh  阅读(290)  评论(0编辑  收藏  举报