题意:求区间第K小值,待查询的区间之间不会有某一个包含另一个情况。
离线处理,把所有查询按左端点的大小排序,由条件可以得出排序后所有查询的右端点一定也是递增的。那我们就可以按顺序处理这些查询,同时更新treap,而且每个元素最多被插入到treap中一次,最多被删除一次。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int maxn = 100000 + 10;
struct node
{
node * ch[2];
int r, v, s;
inline bool operator < (const node & rhs) const { return r < rhs.r; }
inline int cmp(int x) const
{
if(x == v) return -1;
return x < v ? 0 : 1;
}
inline void pushup()
{
s = 1;
if(ch[0] != NULL) s += ch[0]->s;
if(ch[1] != NULL) s += ch[1]->s;
}
};
struct pp
{
int l, r, k, ord;
bool operator < (const pp & rhs) const { return l < rhs.l; }
}que[maxn];
int n, m, num[maxn], ans[maxn];
node * root;
inline void rotate(node * & o, int d) // d = 0 左旋 d = 1 右旋
{
node * k = o->ch[d ^ 1]; o->ch[d ^ 1] = k->ch[d]; k->ch[d] = o; o = k; k->ch[d]->pushup(); k->pushup();
}
void insert(node * & o, int x)
{
if(o == NULL) { o = new node(); o->ch[0] = o->ch[1] = NULL; o->v = x; o->r = rand(); }
else
{
int d = (x < o->v) ? 0 : 1;
insert(o->ch[d], x);
if(o->ch[d]->r > o->r) rotate(o, d ^ 1);
}
o->pushup();
}
void remove(node * & o, int x)
{
if(o == NULL) return;
int d = ((x < o->v) ? 0 : 1);
if(o->v == x)
{
if(o->ch[0] == NULL) { o = o->ch[1]; }
else if(o ->ch[1] == NULL) { o = o->ch[0]; }
else
{
int d2 = (o->ch[0]->r > o->ch[1]->r) ? 1 : 0;
rotate(o, d2); remove(o->ch[d2], x);
}
}
else remove(o->ch[d], x);
if(o != NULL) o->pushup();
}
int findk(node * o, int k)
{
int tmp = 0;
if(o->ch[0] != NULL) { tmp += o->ch[0]->s; if(tmp >= k) return findk(o->ch[0], k); }
tmp++; if(tmp == k) return o->v;
if(o->ch[1] != NULL) { return findk(o->ch[1], k - tmp); }
return -1;
}
int main()
{
freopen("in", "r", stdin);
while(~scanf("%d %d", &n, &m))
{
root = NULL;
for(int i = 1; i <= n; ++i) scanf("%d", num + i);
for(int i = 0; i < m; ++i) { scanf("%d %d %d", &que[i].l, &que[i].r, &que[i].k); que[i].ord = i; }
sort(que, que + m);
int l = que[0].l, r = que[0].l;
for(int i = 0; i < m; ++i)
{
while(l < que[i].l) { remove(root, num[l]); l++; }
while(r <= que[i].r) { insert(root, num[r]); r++; }
//cout << l << " " << r << "\n";
ans[que[i].ord] = findk(root, que[i].k);
}
for(int i = 0; i < m; ++i)
printf("%d\n", ans[i]);
}
return 0;
}
/*
7 2
1 5 2 6 3 7 4
1 5 3
2 7 1
3
2
*/