http://poj.org/problem?id=2892
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #define maxn 51000 5 using namespace std; 6 7 int stack1[maxn],top; 8 struct node 9 { 10 int l,r; 11 int len,ren; 12 }p[maxn*4]; 13 14 void up(int i) 15 { 16 p[i].len=p[i<<1].len; p[i].ren=p[i<<1|1].ren; 17 if(p[i<<1].len==(p[i<<1].r-p[i<<1].l+1)) 18 p[i].len+=p[i<<1|1].len; 19 if(p[i<<1|1].ren==(p[i<<1|1].r-p[i<<1|1].l+1)) 20 p[i].ren+=p[i<<1].ren; 21 } 22 void build_tree(int i,int l,int r) 23 { 24 p[i].l=l; p[i].r=r; 25 if(l==r) 26 { 27 p[i].len=p[i].ren=1; 28 return ; 29 } 30 int mid=(l+r)>>1; 31 build_tree(i<<1,l,mid); 32 build_tree(i<<1|1,mid+1,r); 33 up(i); 34 } 35 36 void update(int id,int i,int oper) 37 { 38 if(p[i].l==p[i].r) 39 { 40 p[i].len=p[i].ren=oper; 41 return; 42 } 43 int mid=(p[i].l+p[i].r)>>1; 44 if(id<=mid) 45 update(id,i<<1,oper); 46 else 47 update(id,i<<1|1,oper); 48 up(i); 49 } 50 51 int search1(int id,int i) 52 { 53 if(p[i].l==p[i].r) 54 return p[i].len; 55 int mid=(p[i].l+p[i].r)>>1; 56 if(id<=mid) 57 { 58 if(p[i<<1].r-p[i<<1].ren+1<=id) 59 return p[i<<1].ren+p[i<<1|1].len; 60 else 61 search1(id,i<<1); 62 } 63 else 64 { 65 if(p[i<<1|1].len+p[i<<1|1].l-1>=id) 66 return p[i<<1].ren+p[i<<1|1].len; 67 else 68 search1(id,i<<1|1); 69 } 70 } 71 72 int main() 73 { 74 int n,q,a; 75 while(scanf("%d%d",&n,&q)!=EOF) 76 { 77 build_tree(1,1,n); 78 top=1; 79 getchar(); 80 while(q--) 81 { 82 char ch; 83 scanf("%c",&ch); 84 if(ch=='D') 85 { 86 scanf("%d",&a); 87 update(a,1,0); 88 stack1[top++]=a; 89 } 90 else if(ch=='Q') 91 { 92 scanf("%d",&a); 93 printf("%d ",search1(a,1)); 94 } 95 else if(ch=='R') 96 { 97 if(top>1) 98 { 99 update(stack1[--top],1,1); 100 } 101 } 102 getchar(); 103 } 104 } 105 return 0; 106 }