P3834 【模板】可持久化线段树 2(主席树)

题意

静态查询区间第 k k k小,多组询问

分析

离散化后建立权值线段树,注意空间要开 n l o g n nlog_n nlogn倍。
每次计算左区间的数个数,如果 c n t ≤ k cnt\le k cntk,则表示第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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值