题意
静态查询区间第 k k k小,多组询问
分析
离散化后建立权值线段树,注意空间要开
n
l
o
g
n
nlog_n
nlogn倍。
每次计算左区间的数个数,如果
c
n
t
≤
k
cnt\le k
cnt≤k,则表示第k个数在左区间,否则在右区间。
代码
#include <iostream>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <iomanip>
#include <map>
#include <cstdio>
#include <stack>
#include <set>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int ,int > pii;
#define endl '\n'
ll gcd(ll a, ll b){
return b == 0 ? a : gcd(b, a % b);
}
void input(){
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
}
inline int read(){
int x=0,f=1;char c=getchar();
while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}
while (c>='0'&&c<='9') x=(x<<3)+(x<<1)+(c^48),c=getchar();
return x*f;
}
const int N = 1e6+10, M = N * 2, inf = 1e8;
int n, m, a[N], num[N], cnt;
int find(int x){
return lower_bound(num+1, num+cnt+1, x) - num;
}
struct Node{
int l, r, cnt;
}tr[N*10];
int root[N]; // 存每棵树的根节点
int idx;
int build(int l, int r){
int p = ++idx;
if(l == r) return p;
int mid = (l + r) >> 1;
tr[p].l = build(l, mid);
tr[p].r = build(mid + 1, r);
return p;
}
void pushup(int u){
tr[u].cnt = tr[tr[u].l].cnt + tr[tr[u].r].cnt;
}
int insert(int p, int l, int r, int x){
int q = ++idx;
tr[q] = tr[p];
if(l == r){
tr[q].cnt++;
return q;
}
int mid = (l + r) >> 1;
if(x <= mid) tr[q].l = insert(tr[p].l, l, mid, x);
else tr[q].r = insert(tr[p].r, mid + 1, r, x);
pushup(q);
return q;
}
int query(int R, int L, int l, int r, int k){
if(l == r) return r;
int cnt = tr[tr[R].l].cnt - tr[tr[L].l].cnt;
int mid = (l + r) >> 1;
// 左儿子数量 >= k,当前值在左子树,否则在右子树
if(k <= cnt) return query(tr[R].l, tr[L].l, l, mid, k);
else return query(tr[R].r, tr[L].r, mid + 1, r, k-cnt);
}
int main(){
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
input();
cin>>n>>m;
for(int i = 1; i <= n; i++){
cin>>a[i];
num[++cnt] = a[i];
}
sort(num + 1, num + cnt + 1);
cnt = unique(num + 1, num + cnt + 1) - num - 1;
root[0] = build(0, cnt);
for(int i = 1; i <= n; i++){
root[i] = insert(root[i-1], 0, cnt, find(a[i]));
}
while(m--){
int l, r, k; cin>>l>>r>>k;
int x = query(root[r], root[l-1], 0, cnt, k);
cout<<num[x]<<endl;
}
return 0;
}