Description
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
Hint
This problem has huge input,so please use c-style input(scanf,printf),or you may got time limit exceed.
Source
Northeastern Europe 2004, Northern Subregion
//题意其实是找第k小的数
//上面是poj的题目描述,HDU的是多组数据 淦
题解
主席树一发。。
poj一遍过,但是在HDU上RE了很长时间(在HDU上一开始是MLE的,然而空间改小以后变成了RE,改一改又把空间开大就A了好坑啊)
这题本来要离散化的,但是把数组排一下序可以代替离散
CODE:
(HDU)
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1e5+10;
const int maxn=2e6;
int a[N],s[N];
int l[maxn],r[maxn];
int root[N],size[maxn];
int n,m,q,x,y,z,tot;
inline void init()
{
memset(l,0,sizeof(l));
memset(r,0,sizeof(r));
memset(root,0,sizeof(root));
memset(size,0,sizeof(size));
tot=0;
}
void add(int &now,int pre,int L,int R,int num)
{
now=++tot;
size[now]=size[pre]+1;
if(L==R) return;
int mid=(L+R)>>1;
if(num<=s[mid]) add(l[now],l[pre],L,mid,num),r[now]=r[pre];
else add(r[now],r[pre],mid+1,R,num),l[now]=l[pre];
}
int ask(int now,int pre,int L,int R,int k)
{
if(L==R) return s[L];
int mid=(L+R)>>1,tmp=size[l[now]]-size[l[pre]];
if(k<=tmp) return ask(l[now],l[pre],L,mid,k);
return ask(r[now],r[pre],mid+1,R,k-tmp);
}
int main()
{
scanf("%d",&q);
while(q--)
{
init();
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
memcpy(s,a,sizeof(a));
sort(s+1,s+n+1);
for(int i=1;i<=n;i++)
add(root[i],root[i-1],1,n,a[i]);
while(m--)
{
scanf("%d%d%d",&x,&y,&z);
printf("%d\n",ask(root[y],root[x-1],1,n,z));
}
}
return 0;
}