You are working for Macrohard company in data structures department. After failing your previous task about key insertion you were asked to write a new data structure that would be able to return quickly k-th order statistics in the array segment.
That is, given an array a[1...n] of different integer numbers, your program must answer a series of questions Q(i, j, k) in the form: "What would be the k-th number in a[i...j] segment, if this segment was sorted?" For example, consider the array a = (1, 5, 2, 6, 3, 7, 4). Let the question be Q(2, 5, 3). The segment a[2...5] is (5, 2, 6, 3). If we sort this segment, we get (2, 3, 5, 6), the third number is 5, and therefore the answer to the question is 5.
Input
The first line of the input file contains n --- the size of the array, and m --- the number of questions to answer (1 <= n <= 100 000, 1 <= m <= 5 000).
The second line contains n different integer numbers not exceeding 109 by their absolute values --- the array for which the answers should be given. The following m lines contain question descriptions, each description consists of three numbers: i, j, and k (1 <= i <= j <= n, 1 <= k <= j - i + 1) and represents the question Q(i, j, k).
Output
For each question output the answer to it --- the k-th number in sorted a[i...j] segment.
Sample Input
7 3 1 5 2 6 3 7 4 2 5 3 4 4 1 1 7 3
Sample Output
5 6 3
题意;查询区间内第k大的数
解析:裸的主席树,详见代码实现,我给了注释
代码
#include<cstdio> #include<cstring> #include<string> #include<algorithm> using namespace std; const int maxn=100005; int N,M,A[maxn],B[maxn]; struct Tree { Tree *lson,*rson; int a,s; //a这个数的个数,s是<=这个数的个数 Tree(){ a=s=0; lson=rson=NULL; } void pushup() { s=a; if(lson) s+=lson->s; if(rson) s+=rson->s; } }*null=new Tree(),*r[maxn]={NULL},data[maxn*20]; int tree_id; void Update(Tree* &y,Tree* &x,int le,int ri,int v) { if(x==NULL) x=null; y=&data[++tree_id]; //创建新节点 *y=Tree(); int mid=(le+ri)/2; if(le==ri) //到达叶子节点 { *y=*x; //有可能x并不是null,而且s和a也不一定为0 y->s++; y->a++; //加1 return; } if(v<=B[mid]) //在左边 { Update(y->lson,x->lson,le,mid,v); y->rson=x->rson; //右边是完全一样的,为了节约空间 y->pushup(); //更新一下 } else //右边同理 { Update(y->rson,x->rson,mid+1,ri,v); y->lson=x->lson; y->pushup(); } } int Query(Tree* &x,Tree* &y,int le,int ri,int kth) { if(x==NULL) x=null; if(y==NULL) y=null; if(le==ri) return B[le]; //找到了 int mid=(le+ri)/2; int cnt=0; if(y->lson) cnt+=y->lson->s; //先加整段到y的 if(x->lson) cnt-=x->lson->s; //减掉到x-1的 if(cnt>=kth) return Query(x->lson,y->lson,le,mid,kth); //左边足够 else return Query(x->rson,y->rson,mid+1,ri,kth-cnt); //右边 } int main() { null->lson=null; null->rson=null;//指向自己 tree_id=0; scanf("%d%d",&N,&M); for(int i=1;i<=N;i++) { scanf("%d",&A[i]); B[i]=A[i]; } sort(B+1,B+N+1); int k=1; for(int i=2;i<=N;i++) if(B[i]!=B[k]) B[++k]=B[i]; //离散化 for(int i=1;i<=N;i++) Update(r[i],r[i-1],1,k,A[i]); //更新 for(int i=1;i<=M;i++) { int x,y,kth; //查询[x,y]第kth的数 scanf("%d%d%d",&x,&y,&kth); printf("%d\n",Query(r[x-1],r[y],1,k,kth)); } return 0; }