HDU - 2665 Kth number 主席树题解

Description

Give you a sequence and ask you the kth big number of a inteval.

Input

The first line is the number of the test cases.
For each test case, the first line contain two integer n and m (n, m <= 100000), indicates the number of integers in the sequence and the number of the quaere.
The second line contains n integers, describe the sequence.
Each of following m lines contains three integers s, t, k.
[s, t] indicates the interval and k indicates the kth big number in interval [s, t]

Output

For each test case, output m lines. Each line contains the kth big number.

Sample Input

1
10 1
1 4 2 3 5 6 7 8 9 0
1 3 2

Sample Output

2


显然就是一道主席树裸题,鉴于很多做这道题的朋友都是刚开始学主席树,我在这里写一下代码注释


#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
#include<set>
const int MAXN=100000*20;
using namespace std;
struct Tree{
    int L,R,sum;
}tree[MAXN];
int xx,yy,kk,n,m,T,sz,a[MAXN],root[MAXN];
vector<int>v;
int id(int x){
    return lower_bound(v.begin(),v.end(),x)-v.begin()+1;
}
void modify(int x,int &y,int loc,int l,int r){
    tree[++sz]=tree[x];y=sz;tree[y].sum++;//新建一棵树,它等于上一棵树,然后再进行更改,这棵树由于插入了一个数,所以sum++
    if(l==r) return;//如果递归到底层,那么就回去啦
    int mid=(l+r)>>1;
    if(loc<=mid) modify(tree[x].L,tree[y].L,loc,l,mid);//看插入在左边还是插入在右边
    else         modify(tree[x].R,tree[y].R,loc,mid+1,r);
}

int query(int x,int y,int k,int l,int r){
    if(l==r) return l;//如果查到底层,就返回位置,注意这里返回的是离散化后的坐标
    int t=tree[tree[y].L].sum-tree[tree[x].L].sum;
    int mid=(l+r)>>1;
    if(t>=k) query(tree[x].L,tree[y].L,k,l,mid);//分左右递归查询
    else     query(tree[x].R,tree[y].R,k-t,mid+1,r);
}
int main(){
    scanf("%d",&T);
    while(T--){
        sz=0;v.clear();scanf("%d%d",&n,&m);
        for(register int i=1;i<=n;i++) scanf("%d",&a[i]),v.push_back(a[i]);
        sort(v.begin(),v.end());v.erase(unique(v.begin(),v.end()),v.end());
        //这里是在离散化,离散到一个vector里面去然后去重,这样就可以知道序号来进行操作啦
        for(register int i=1;i<=n;i++) modify(root[i-1],root[i],id(a[i]),1,n);//用前一棵树来建后一棵树,放的数是id(a[i]),也就是离散化后的下标
        for(register int i=1;i<=m;i++){
            scanf("%d%d%d",&xx,&yy,&kk);
            printf("%d\n",v[query(root[xx-1],root[yy],kk,1,n)-1]);//注意这里要减1,原因是vector是从0开始存的
        }
    }
    return 0;
}

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值