某谷链接
发一篇博客记录一下主席树板子。
别忘了输出原数组中的元素,而不是离散化后的。
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("")
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define rg register
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 1e5 + 5;
const int maxt = 2e6 + 5;
inline ll read()
{
ll ans = 0;
char ch = getchar(), last = ' ';
while(!isdigit(ch)) last = ch, ch = getchar();
while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
if(last == '-') ans = -ans;
return ans;
}
inline void write(ll x)
{
if(x < 0) x = -x, putchar('-');
if(x >= 10) write(x / 10);
putchar(x % 10 + '0');
}
int n, m, a[maxn], b[maxn];
struct Tree
{
int ls, rs, sum;
}t[maxt];
int root[maxn], cnt = 0;
void insert(int old, int& now, int l, int r, int d)
{
t[now = ++cnt] = t[old];
t[now].sum++;
if(l == r) return;
int mid = (l + r) >> 1;
if(d <= mid) insert(t[old].ls, t[now].ls, l, mid, d);
else insert(t[old].rs, t[now].rs, mid + 1, r, d);
}
int query(int old, int now, int l, int r, int id)
{
if(l == r) return l;
int mid = (l + r) >> 1, del = t[t[now].ls].sum - t[t[old].ls].sum;
if(id <= del) return query(t[old].ls, t[now].ls, l, mid, id);
else return query(t[old].rs, t[now].rs, mid + 1, r, id - del);
}
int main()
{
n = read(); m = read();
for(int i = 1; i <= n; ++i) a[i] = b[i] = read();
sort(b + 1, b + n + 1);
int _n = unique(b + 1, b + n + 1) - b - 1;
for(int i = 1; i <= n; ++i)
a[i] = lower_bound(b + 1, b + _n + 1, a[i]) - b;
for(int i = 1; i <= n; ++i) insert(root[i - 1], root[i], 1, _n, a[i]);
for(int i = 1, L, R, k; i <= m; ++i)
{
L = read(); R = read(); k = read();
write(b[query(root[L - 1], root[R], 1, _n, k)]), enter;
}
return 0;
}