poj 2892 树状数组 二分
代码很好懂,不解释了
View Code
#include<cstdio> #include<cstring> const int maxn = 50010; int c[maxn]; void add(int x,int d) { for(;x<maxn;x+=x&-x) c[x]+=d; } int sum(int x) { int ans=0; for(;x>0;x-=x&-x) ans+=c[x]; return ans; } int bin(int val,int n) { int l=1,r=n+1,best=n+2; while(l<=r) { int m=(l+r)>>1; if(sum(m)>=val) { best=m; r=m-1; } else l=m+1; } return best; } int st[maxn]; bool flag[maxn]; int main() { int n,m,i,j,x; char op[5]; while(scanf("%d%d",&n,&m)!=EOF) { int tot=0; memset(flag,0,sizeof(flag)); memset(c,0,sizeof(c)); while(m--) { scanf("%s",op); if(op[0]=='D') { scanf("%d",&x); x++; st[++tot]=x; flag[x]=true; add(x,1); } else if(op[0]=='R') { x=st[tot--]; flag[x]=false; add(x,-1); } else { scanf("%d",&x); x++; if(flag[x]){ printf("0\n");continue;} x=sum(x); int pos1=bin(x,n); int pos2=bin(x+1,n); printf("%d\n",pos2-pos1-1); } } } return 0; }