-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsegment-tree-persistente
62 lines (51 loc) · 1.49 KB
/
segment-tree-persistente
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <cstdio>
#include <algorithm>
using namespace std;
typedef pair<int, int> ii;
struct node {
int v;
node *l, *r;
node(int _v, node *_l, node *_r) : v(_v), l(_l), r(_r) { }
};
const int MAXN =1e5+5;
int N, Q, A[MAXN];
ii v[MAXN];
node* ver[MAXN];
int l, r, k;
node* build_pst(int L, int R) {
if(L == R) return new node(0, NULL, NULL);
int mid = (L+R)/2;
return new node(0, build_pst(L, mid), build_pst(mid+1, R));
}
node* update_pst(node *prev, int L, int R, int p, int v) {
if(L == R) return new node(v, NULL, NULL);
int mid = (L+R)/2;
node *n = new node(0, prev->l, prev->r);
if(p <= mid) n->l = update_pst(prev->l, L, mid, p, v);
else n->r = update_pst(prev->r, mid+1, R, p, v);
n->v = n->l->v + n->r->v;
return n;
}
int kth_pst(node *bef, node *af, int L, int R, int k) {
if(L == R) return L;
int a = af->l->v - bef->l->v;
int mid = (L+R)/2;
if(k<=a) return kth_pst(bef->l, af->l, L, mid, k);
return kth_pst(bef->r, af->r, mid+1, R, k-a);
}
int main() {
scanf("%d%d", &N, &Q);
for(int i = 0; i < N; i++) {
scanf("%d", &A[i]);
v[i] = ii(A[i], i);
}
sort(v, v+N);
for(int i = 0; i < N; i++) A[v[i].second] = i;
ver[0]=build_pst(0, N-1);
for(int i = 0; i < N; i++) ver[i+1] = update_pst(ver[i], 0, N-1, A[i], 1);
for(int i = 0; i < Q; i++) {
scanf("%d%d%d", &l, &r, &k);
int a = kth_pst(ver[l-1], ver[r], 0, N-1, k);
printf("%d\n", v[a].first);
}
}