三个入门博客:
学习完上面的博客,下面的代码也就不难看明白了。
#include <bits/stdc++.h>
using namespace std;
//#define map unordered_map
//#define int long long
const int N = 1e5 + 10;
int a[N], n, m;
vector<int> nums;
int root[N];
int idx;
struct node
{
int l, r;
int cnt;
} t[(N << 2) + N * 17];
inline void Clear() { //多组测试样例应当清空 这个很重要
idx = 0;
nums.clear();
for (int i = 0; i < n * 4 + n * 17; ++i)
{
t[i].l = t[i].r = t[i].cnt = 0;
}
}
int find(int x) {
return lower_bound(nums.begin(), nums.end(), x) - nums.begin();
}
int build(int l, int r)
{
int p = ++idx;
if (l == r) {
return p;
}
int mid = l + r >> 1;
t[p].l = build(l, mid), t[p].r = build(mid + 1, r);
return p;
}
int insert(int p, int l, int r, int x)
{
int q = ++idx;
t[q] = t[p];
if (l == r) {
t[q].cnt++;
return q;
}
int mid = l + r >> 1;
if (x <= mid) t[q].l = insert(t[p].l, l, mid, x);
else t[q].r = insert(t[p].r, mid + 1, r, x);
t[q].cnt = t[t[q].l].cnt + t[t[q].r].cnt;
return q;
}
int ask(int q, int p, int l, int r, int k)
{
if (l == r) return r;
int cnt = t[t[q].l].cnt - t[t[p].l].cnt;
int mid = l + r >> 1;
if (k <= cnt) return ask(t[q].l, t[p].l, l, mid, k);
else return ask(t[q].r, t[p].r, mid + 1, r, k - cnt);
}
signed main()
{
int T; cin >> T;
while (T--)
{
scanf("%d%d", &n, &m);
Clear();
for (int i = 1; i <= n; ++i)
{
scanf("%d", &a[i]);
nums.emplace_back(a[i]);
}
sort(nums.begin(), nums.end());
nums.erase(unique(nums.begin(), nums.end()), nums.end());
root[0] = build(0, nums.size() - 1);
for (int i = 1; i <= n; ++i)
{
root[i] = insert(root[i - 1], 0, nums.size() - 1, find(a[i]));
}
while (m--)
{
int l, r, k;
scanf("%d%d%d", &l, &r, &k);
int ans = ask(root[r], root[l - 1], 0, nums.size() - 1, k);
printf("%d\n", nums[ans]);
}
}
return 0;
}