Given a sequence, evaluate the k-th Small Interval
Note that the K is small !! Don't be fooled by the topic description !! This question is K small !! It's not K big !!!
This question is the same as that of poj2104. It is used to calculate the k-th smaller range. The difference is that the sequence of this question is repeated.
For duplicated values, we must first pre-process the number of medians that can enter the left interval, otherwise, excessive medians are accumulated in the left range, and the entry into the left range is pushed to the right range.
In fact, I just want to explain why it is so troublesome to repeat the processing on the Internet... Is it possible to scale down something like me?
#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#define M 100100using namespace std;int n,m,a[M],b[M],c[M];int s[20][M];void Build_Tree(int l,int r,int dpt){ int i,mid=l+r>>1; if(l==r) return ; int l1=l,l2=mid+1,left=mid-l+1; for(i=l;i<=r;i++) left-=(a[i]<c[mid]); for(i=l;i<=r;i++) { if(a[i]>c[mid]||a[i]==c[mid]&&!left) b[l2++]=a[i],s[dpt][i]=(i==l?0:s[dpt][i-1] ); else b[l1++]=a[i],s[dpt][i]=(i==l?1:s[dpt][i-1]+1),left-=(a[i]==c[mid]); } memcpy( a+l , b+l , sizeof(a[0])*(r-l+1) ); Build_Tree(l,mid,dpt+1); Build_Tree(mid+1,r,dpt+1);}int getans(int l,int r,int dpt,int x,int y,int k){ int mid=l+r>>1; if(l==r) return c[mid]; int l1=(x==l?0:s[dpt][x-1]),l2=s[dpt][y]; if(k<=l2-l1) return getans(l,mid,dpt+1,l+l1,l+l2-1,k); else return getans(mid+1,r,dpt+1,(mid+1)+(x-l-l1),(mid+1)+(y-l+1-l2)-1,k-l2+l1);}int main(){ int T,i,x,y,k; for(cin>>T;T;T--) { cin>>n>>m; for(i=1;i<=n;i++) scanf("%d",&a[i]),c[i]=a[i]; sort(c+1,c+n+1); Build_Tree(1,n,0); for(i=1;i<=m;i++) scanf("%d%d%d",&x,&y,&k),printf("%d\n", getans(1,n,0,x,y,k ) ); }}
HDU 2665 kth number partition tree