还是线段树,不过有点复杂,虐了我两天,WA了无数次,呵呵。 #include <iostream> #include <vector> #include <stack> using namespace std; struct node { int left,right,lval,rval,cval; int dis() { return right-left+1; } }st[150001]; int n,m; char s[2]; void bulid(int x,int y,int pos) { st[pos].left=x;st[pos].right=y; st[pos].lval=st[pos].rval=st[pos].cval=y-x+1; if(x==y) return; else { bulid(x,(x+y)/2,pos<<1); bulid((x+y)/2+1,y,pos<<1|1); } } void update(int root,int y,int x) { if(st[root].left==st[root].right) { st[root].lval=st[root].rval=st[root].cval=y ? 0 : st[root].dis(); return; } int mid=(st[root].left+st[root].right)/2; if(x <= mid) update(root<<1,y,x); else update(root<<1|1,y,x); int l=root<<1; int r=root<<1|1; st[root].cval=max((st[l].rval+st[r].lval),max(st[l].cval,st[r].cval)); st[root].lval=st[l].lval;st[root].rval=st[r].rval; if(st[l].cval==st[l].dis()) st[root].lval+=st[r].lval; if(st[r].cval==st[r].dis()) st[root].rval+=st[l].rval; } int ans(int root,int x) { if(st[root].left==st[root].right||st[root].cval==st[root].dis()||st[root].cval==0) return st[root].cval; int mid=(st[root].right+st[root].left)/2; if(x<=mid) { if(x > st[root<<1].right-st[root<<1].rval) return ans(root<<1,x)+ans(root<<1|1,st[root<<1|1].left); else return ans(root<<1,x); } else { if(x < st[root<<1|1].left+st[root<<1|1].lval) return ans(root<<1,st[root<<1].right)+ans(root<<1|1,x); else return ans(root<<1|1,x); } } stack <int> ss; int main() { while(scanf("%d%d",&n,&m)==2) { int i,a;bulid(1,n,1); for(i=1;i<=m;i++){ scanf("%s",s); if(s[0]=='D'){ scanf("%d",&a); ss.push(a); update(1,1,a); } else if(s[0]=='Q'){ scanf("%d",&a); printf("%d/n",ans(1,a)); } else{ if(ss.empty()) continue; update(1,0,ss.top()); ss.pop(); } } } return 0; }