-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWavelet Tree.cpp
More file actions
73 lines (64 loc) · 1.44 KB
/
Wavelet Tree.cpp
File metadata and controls
73 lines (64 loc) · 1.44 KB
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
63
64
65
66
67
68
69
70
71
72
73
#include <bits/stdc++.h>
using namespace std;
void fastIO() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
}
typedef vector<int>::iterator itr;
struct wavelet {
wavelet *l, *r;
vector<int> f;
int lo, hi;
void build(itr st, itr dr, int x, int y) {
lo = x, hi = y;
if (x == y)
return;
f.reserve(dr - st + 1);
int mid = (x + y) >> 1;
auto check = [&](int v) {
return v <= mid;
};
f.push_back(0);
for (itr it = st; it != dr; ++it)
f.push_back(f.back() + check(*it));
itr pivot = stable_partition(st, dr, check);
if (st < pivot) {
l = new wavelet;
l->build(st, pivot, x, mid);
}
if (pivot < dr) {
r = new wavelet;
r->build(pivot, dr, mid + 1, y);
}
}
int kth(int st, int dr, int k) {
if (lo == hi)
return lo;
int lb = f[st - 1], rb = f[dr];
int in_left = rb - lb;
if (k <= in_left)
return l->kth(lb + 1, rb, k);
return r->kth(st - lb, dr - rb, k - in_left);
}
};
void solve() {
int N, Q;
cin >> N >> Q;
vector<int> a(N + 1);
for (int i = 1; i <= N; ++i)
cin >> a[i];
wavelet wt;
wt.build(a.begin() + 1, a.end(), *min_element(a.begin() + 1, a.end()), *max_element(a.begin() + 1, a.end()));
for (int i = 0; i < Q; ++i) {
int l, r, k;
cin >> l >> r >> k;
++l, ++k;
cout << wt.kth(l, r, k) << '\n';
}
}
int main() {
fastIO();
solve();
return 0;
}