# poj 2104 K-th Number

// poj 2104 K-th Number
// ac 16344K 907MS
#include<cstdio>
#include<algorithm>
using namespace std;

#define FORE(i, a, b) for(i = a; i <= b; ++i)
const int N = 100000 + 10;

struct NODE {
int l,r;
}tr[N * 4];
int data[N], seg[20][N], lessMid[20][N];

void Build(int l, int r, int root, int d) {
tr[root].l = l, tr[root].r = r;
if( l == r )
return;
int i, mid = (l + r) >> 1;
int lsame = mid - l + 1;   //这个变量表示左边最多可放几个与data[mid]相同的数
FORE(i, l, r) //得出实际能放几个相同的数
if( seg[d][i] < data[mid] )
--lsame;
int tl = l, tr = mid + 1, same = 0;
FORE(i, l, r) {
if( i == l )
lessMid[d][i] = 0;  //表示在[L，R]内有几个数小于等于data[mid]
else
lessMid[d][i] = lessMid[d][i - 1];
if( seg[d][i] < data[mid] ) {
++lessMid[d][i];
seg[d + 1][tl++] = seg[d][i];
}
else if( seg[d][i] > data[mid] )
seg[d + 1][tr++] = seg[d][i];
else {
if( same < lsame ) {
++same, ++lessMid[d][i];
seg[d + 1][tl++] = seg[d][i];
}
else
seg[d + 1][tr++] = seg[d][i];
}
}
Build(l, mid, root * 2, d + 1);
Build(mid + 1, r, root * 2 + 1, d + 1);
}

int Query(int l, int r, int root, int d, int cnt) {
if( l == r )
return seg[d][l];
int s;   //表示在[l，r]内有几个小于等于data[mid]的个数
int ss;  //表示在[tr[root].l,l-1]内有几个小于等于data[mid]的个数
if( l == tr[root].l ) {
s = lessMid[d][r];
ss = 0;
}
else {
s = lessMid[d][r] - lessMid[d][l - 1];
ss = lessMid[d][l - 1];
}
if( s >= cnt )
return Query(tr[root].l + ss, tr[root].l + ss + s - 1, root * 2, d + 1, cnt);
else {
int mid = (tr[root].l + tr[root].r) >> 1;
int bb = l - tr[root].l - ss;  //表示 [tr[root].l , l-1 ]有多少个分到右边
int b = r - l + 1 - s;           //表示 [l , r]有多少个分到右边
return Query(mid + bb + 1, mid + bb + b, 2 * root + 1, d + 1 ,cnt - s);
}
}

int main() {
int n, m, l, r, cnt, i;
while(scanf("%d%d", &n, &m) != EOF) {
FORE(i, 1, n) {
scanf("%d", data + i);
seg[1][i] = data[i];
}
sort(data + 1,data + n + 1);
Build(1, n, 1, 1);
while( m-- ) {
scanf("%d%d%d", &l, &r, &cnt);
printf("%d\n", Query(l, r, 1, 1, cnt));
}
}
return 0;
}


11-02 1005

05-03 2301

03-12 495

04-29 1786

08-25 1489

05-17 4486

07-08 638

04-20 1018

12-15 706

02-03 584