POJ2104 K-th Number

本文介绍如何使用主席树解决区间[l,r]内寻找第K小元素的问题。通过构建历史版本的线段树,每棵树代表不同时间点的数据状态,从而实现高效查询。

题目

求区间[l,r]中的第K小的数。

题解

裸的主席树,每一棵树代表着一个历史版本,第i个历史版本的线段树中区间[x,y]的sum值表示原数列[1..i]中的数在整个原数列的排名(从小到大)为[x,y]的个数。
搜索的时候,第r个历史版本的区间[x,y]的值-第l-1个历史版本的区间[x,y]的值在数值上正好等于原数列[l..r]中的数在整个原数列的排名(从小到大)为[x,y]的个数。
详见代码(题解可能写得有点绕)。

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define N 100010
#define fo(i,a,b) for(i=a;i<=b;i++)
using namespace std;
struct note{
    int sum,ls,rs;
};note tr[N*20];
int root[N];
int sgm_tot;
int i,j,k,l,r,n,m,ans;
int a[N],val[N],cnt;
void ins(int px,int py,int l,int r,int x){
    tr[px].sum=tr[py].sum+1;
    if (l==r) return;
    int wz=(l+r)/2;
    if (x<=wz){
        tr[px].ls=++sgm_tot;
        tr[px].rs=tr[py].rs;
        ins(tr[px].ls,tr[py].ls,l,wz,x);
    } else{
        tr[px].ls=tr[py].ls;//主席树通常动态开节点,节省空间。
        tr[px].rs=++sgm_tot;
        ins(tr[px].rs,tr[py].rs,wz+1,r,x);
    }
}
int query(int px,int py,int l,int r,int x){
    if (l==r) return a[l];
    int wz=(l+r)/2;
    if (x>tr[tr[px].ls].sum-tr[tr[py].ls].sum)
        return query(tr[px].rs,tr[py].rs,wz+1,r,x-tr[tr[px].ls].sum+tr[tr[py].ls].sum);
        else
    return query(tr[px].ls,tr[py].ls,l,wz,x);
}
int main(){
    scanf("%d%d",&n,&m);
    fo(i,1,n) scanf("%d",&a[i]);
    memcpy(val,a,sizeof(val));
    sort(a+1,a+n+1);
    cnt=unique(a+1,a+n+1)-a-1;
    fo(i,1,n) val[i]=lower_bound(a+1,a+cnt+1,val[i])-a;
    fo(i,1,n){
        root[i]=++sgm_tot;
        ins(root[i],root[i-1],1,cnt,val[i]);
    }
    fo(i,1,m){
        scanf("%d%d%d",&l,&r,&k);
        ans=query(root[r],root[l-1],1,cnt,k);
        printf("%d\n",ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值