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 62 63 64 65 66 67 68
| #include<cstdio> using namespace std; const int N=1e5,S=1e9; int n,m,a[N+1],tot; struct seg_tree { seg_tree *lson,*rson; int val; }t[(N<<5)+1],*root[N+1]; seg_tree *build(seg_tree *ori,int l,int r,int pos) { int num=++tot; if(ori!=NULL) { t[num]=*ori; } t[num].val+=pos; if(l==r) { return &t[num]; } int mid=(l+r)>>1; if(pos<=mid) { t[num].lson=build(t[num].lson,l,mid,pos); } else { t[num].rson=build(t[num].rson,mid+1,r,pos); } return &t[num]; } int query(seg_tree *from,seg_tree *to,int l,int r,int f,int t) { if(from==NULL) { from=::t; } if(to==NULL) { to=::t; } if((l>=f)&&(r<=t)) { return to->val-from->val; } int mid=(l+r)>>1,res=0; if(f<=mid) { res+=query(from->lson,to->lson,l,mid,f,t); } if(t>mid) { res+=query(from->rson,to->rson,mid+1,r,f,t); } return res; } int main() { scanf("%d",&n); for(int i=1;i<=n;++i) { scanf("%d",&a[i]); } root[0]=&(t[tot=1]=seg_tree{t,t,0}); for(int i=1;i<=n;++i) { root[i]=build(root[i-1],1,S,a[i]); } scanf("%d",&m); for(int l,r;m;--m) { scanf("%d%d",&l,&r); int res=0,tem=0; while(tem>=res) { res=tem+1; tem=query(root[l-1],root[r],1,S,1,res); } printf("%d\n",res); } return 0; }
|