1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| #include <cstdio> #include <cstring> #include <algorithm> const int N = 100010; using namespace std; int read(){ int x = 0,f = 1,c = getchar(); while (c<'0' || c>'9') {if (c=='-') f = -1;c = getchar();} while (c>='0' && c<='9') x = x*10+c-'0',c = getchar(); return x*f; } int n,m,l,r,tot; struct node *null,*rt; struct node{ node *L,*R;int S,fix,val,rev; void Update(){if (this==null) return;S = L->S+R->S+1;} void Setrev(){if (this==null) return;rev^=1;swap(L,R);} void Down(){if (this==null) return;if (rev){rev = 0;L->Setrev();R->Setrev();}} } Nd[N]; typedef pair<node*,node*> Droot; void print(node *x){if (x==null) return;x->Down();print(x->L);printf("%d ",x->val);print(x->R);} node *Build(){ static node *stk[N],*x,*last = null; int top = 0; for (int i=1;i<=n;i++){ tot++;x = Nd+tot;x->val = i;last = null; while (top && stk[top]->fix>x->fix) {stk[top]->Update();last = stk[top];stk[top--] = null;} if (top) stk[top]->R = x;x->L = last;stk[++top] = x; } while (top) stk[top--]->Update(); return stk[1]; } node *Merge(node *A,node *B){ if (A==null && B==null) return null; if (A==null) return B;if (B==null) return A; if (A->fix<B->fix){A->Down();A->R = Merge(A->R,B);A->Update();return A;} else {B->Down();B->L = Merge(A,B->L);B->Update();return B;} } Droot Split(node *x,int k) { if (x==null) return Droot(null,null); Droot y;x->Down(); if (x->L->S>=k) {y = Split(x->L,k);x->L = y.second;x->Update();y.second = x;} else {y = Split(x->R,k-x->L->S-1);x->R = y.first;x->Update();y.first = x;} return y; } void Reverse(int l,int r){ if (l==1 && r==n) {rt->Setrev();return;} if (l==1) {Droot x = Split(rt,r);x.first->Setrev();rt = Merge(x.first,x.second);return;} if (r==n) {Droot x = Split(rt,l-1);x.second->Setrev();rt = Merge(x.first,x.second);return;} Droot x = Split(rt,l-1); Droot y = Split(x.second,r-(l-1)); y.first->Setrev(); rt = Merge(Merge(x.first,y.first),y.second); } int main(){ n = read();m = read();null = Nd; for (int i=0;i<=n;i++) Nd[i] = (node){null,null,1,rand(),0}; null->S = 0;rt = Build(); for (int i=1;i<=m;i++) {l = read();r = read();Reverse(l,r);} print(rt); }
|