关于区间第k大都不知道写过多少版本的程序了,最近刚看了一些可持久化数据结构的资料,就当做基础练习。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 100005;
struct node{
int size;
node * ch[2];
}N[MAXN * 200];
node * root[MAXN];
struct P{
int v,id;
bool operator<(const P &a)const{
return v < a.v;
}
}p[MAXN];
int a[MAXN],num[MAXN];
int L,R,test,k,total,n,m,t;
node * newnode()
{
node * t = &N[total++];
t->size = 0;
t->ch[0] = t->ch[1] = NULL;
return t;
}
inline int getSize(node * t){
return (t==NULL?0:t->size);
}
node * update(int l ,int r, node * last, int v)
{
node * t = newnode();
t->size = getSize(last)+1;
if (l==r) return t;
int m = (l+r)/2;
if (v<=m){
t->ch[1] = last->ch[1];
if (last->ch[0] == NULL) last->ch[0] = newnode();
t->ch[0] = update(l,m,last->ch[0],v);
t->ch[0]->size=getSize(last->ch[0])+1;
} else
{
t->ch[0] = last->ch[0];
if (last->ch[1] == NULL) last->ch[1] = newnode();
t->ch[1] = update(m+1,r,last->ch[1],v);
t->ch[1]->size=getSize(last->ch[1])+1;
}
return t;
}
int query(int l, int r, node * r1, node * r2, int k)
{
if (l==r) return l;
if (r2==NULL) r2 = newnode();
if (r1==NULL) r1 = newnode();
int cnt = getSize(r2->ch[0])- getSize(r1->ch[0]);
int m = (l+r)/2;
if (k<=cnt)
return query(l,m,r1->ch[0], r2->ch[0], k); else
return query(m+1,r,r1->ch[1], r2->ch[1] , k-cnt);
}
void work()
{
scanf("%d%d",&n,&m);
for (int i = 1; i <= n;++i){
scanf("%d",&a[i]);
p[i].v = a[i]; p[i].id = i;
}
sort(p+1,p+n+1);
a[p[1].id] = t = 1;num[1] = p[1].v;
for (int i = 2; i <= n;++i)
{
t += (p[i].v != p[i-1].v);
a[p[i].id] = t;
num[t] = p[i].v;
}
total = 0;
root[0] = newnode();
for (int i = 1; i <= n;++i)
root[i] = update(1,t,root[i-1],a[i]);
for (int i = 1; i <= m; ++i)
{
scanf("%d %d %d", &L, &R, &k);
printf("%d\n",num[query(1,t,root[L-1],root[R],k)]);
}
//for (int i = 0; i < total;++i) delete &N[i];
}
int main()
{
int test; cin>>test;
while (test--){
work();
}
return 0;
}