POJ 2104 K-th Number(划分树)

本文介绍了一种使用划分树解决区间内寻找第K大数值的问题。通过构建划分树并进行查询操作,实现了对给定数组中指定区间内第K大数的有效查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://poj.org/problem?id=2104

给定数组,和任意区间,求这个区间内第K大数

划分树的典型题

划分树具体讲解我是看http://shizhixinghuo.diandian.com/post/2012-09-02/40037691896

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;
const int maxn = 110000;
int rec[maxn];
struct node{
    int left;
    int right;
    int mid;
}tree[maxn*5];
struct point{
    int value;
    int right;
    bool is_right;
}po[20][maxn];
int n,m;
int build_tree(int left,int right,int deepth,int pos){
    tree[pos].left=left;
    tree[pos].right=right;
    tree[pos].mid=(left+right)>>1;
    int mid=rec[tree[pos].mid],l=left,r=tree[pos].mid+1,i,j,k;
    point *now=po[deepth-1],*then=po[deepth];
    for(i=left;i<=right;i++){
        if(now[i].value>mid){
            then[r++].value=now[i].value;
            now[i].is_right=true;
        }else{
            then[l++].value=now[i].value;
            now[i].is_right=false;
        }
    }
    now[left].right=now[left].is_right;
    for(i=left+1;i<=right;i++){
        now[i].right=now[i-1].right+now[i].is_right;
    }
    if(left == right) return 0;
    build_tree(left,tree[pos].mid,deepth+1,pos<<1);
    build_tree(tree[pos].mid+1,right,deepth+1,(pos<<1)+1);
    return 0;
}
int query(int left,int right,int k,int deepth,int pos){
    int num=0;
    point *now=po[deepth];
    if(tree[pos].left == tree[pos].right) return now[tree[pos].left].value;
    num=right-left+1-(now[right].right-now[left].right+now[left].is_right);
    if(num>=k)
    return query(left-now[left].right+now[left].is_right,right-now[right].right,k,deepth+1,pos<<1);
    else
    return query(tree[pos].mid+now[left].right+1-now[left].is_right,\
                 tree[pos].mid+now[right].right,k-num,deepth+1,(pos<<1)+1);
}
int main(){
    int i,j,a,b,k;
    while(scanf("%d%d",&n,&m)!=EOF){
        for(i=1;i<=n;i++){
            scanf("%d",&rec[i]);
            po[0][i].value=rec[i];
        }
        sort(rec+1,rec+1+n);
        build_tree(1,n,1,1);
        while(m--){
            scanf("%d%d%d",&a,&b,&k);
            printf("%d\n",query(a,b,k,0,1));
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值