标签:split swap space def build sync with print node
#include <bits/stdc++.h> #define rev(o) (o)=!(o) using namespace std; struct Node{ int s,k; bool f; Node *son[2]; Node(int m=0){ s=0; k=m; f=false; son[1]=son[0]=NULL; } void maintain(){ s=1; if(son[0]) s+=son[0]->s; if(son[1]) s+=son[1]->s; } void down(){ swap(son[1],son[0]); if(son[0]) rev(son[0]->f); if(son[1]) rev(son[1]->f); f=false; } int cmp(int m){ int d=0; if(son[0]) d=son[0]->s; if(m<=d) return 0; if(m==d+1) return -1; return 1; } }; void rotate(Node *&o,int d){ Node *t; if(o->f) o->down(); t=o->son[d^1]; if(t->f) t->down(); o->son[d^1]=t->son[d]; t->son[d]=o; o->maintain(); t->maintain(); o=t; } void splay(Node *&o,int k){ int d1,d2,k2=k,k3; if(o->f) o->down(); d1=o->cmp(k); if(!~d1||!o->son[d1]) return; if(o->son[d1]->f) o->son[d1]->down(); if(d1){ k2--; if(o->son[0]) k2-=o->son[0]->s; } d2=o->son[d1]->cmp(k2); if(!~d2||!o->son[d1]->son[d2]){ rotate(o,d1^1); return; } k3=k2; if(d2){ k3--; if(o->son[d1]->son[0]) k3-=o->son[d1]->son[0]->s; } splay(o->son[d1]->son[d2],k3); if(d1==d2){ rotate(o,d1^1); rotate(o,d2^1); } else { rotate(o->son[d1],d1); rotate(o,d2); } } Node* merge(Node *l,Node *r){ splay(l,l->s); l->son[1]=r; l->maintain(); return l; } void split(Node *o,Node *&l,Node *&r,int k){ splay(o,k); l=o; r=o->son[1]; l->son[1]=NULL; l->maintain(); } void reverse(Node *&o,int l,int r){ splay(o,r+2); splay(o->son[0],l); rev(o->son[0]->son[1]->f); } void print(Node *o){ if(!o) return; if(o->f) o->down(); print(o->son[0]); if(o->k) cout<<o->k<<‘ ‘; print(o->son[1]); } void build(Node *&o,int n){ for(;n;n--) o=merge(new Node(n),o); o=merge(o,new Node()); o=merge(new Node(),o); } int main(){ int n,m; Node *root=NULL; ios::sync_with_stdio(false); cin.tie(0); cin>>n>>m; build(root,n); while(m--){ int l,r; cin>>l>>r; reverse(root,l,r); } print(root); return 0; }
标签:split swap space def build sync with print node
原文地址:http://www.cnblogs.com/HC-LittleJian/p/7999489.html