可持久化数据结构之线段树 hdu2665 poj2104

关于区间第k大都不知道写过多少版本的程序了,最近刚看了一些可持久化数据结构的资料,就当做基础练习。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>


using namespace std;
const int MAXN = 100005;
struct node{
       int size;
       node * ch[2];
}N[MAXN * 200];
node * root[MAXN];
struct P{
       int v,id;
       bool operator<(const P &a)const{
            return v < a.v;
       }
}p[MAXN];
int a[MAXN],num[MAXN];
int L,R,test,k,total,n,m,t;
node * newnode()
{
     node * t = &N[total++];
     t->size = 0;
     t->ch[0] = t->ch[1] = NULL;
     return t;
}
inline int getSize(node * t){
       return (t==NULL?0:t->size);
}
node * update(int l ,int r, node * last, int v)
{
     node * t = newnode();
     t->size = getSize(last)+1;
     if (l==r) return t;
     int m = (l+r)/2;
     if (v<=m){
            t->ch[1] = last->ch[1];
            if (last->ch[0] == NULL) last->ch[0] = newnode();
            t->ch[0] = update(l,m,last->ch[0],v);
            t->ch[0]->size=getSize(last->ch[0])+1;
     } else
     {
            t->ch[0] = last->ch[0];
            if (last->ch[1] == NULL) last->ch[1] = newnode();
            t->ch[1] = update(m+1,r,last->ch[1],v);
            t->ch[1]->size=getSize(last->ch[1])+1;
     }
     return t;
}
int  query(int l, int r, node * r1, node * r2, int k)
{
     if (l==r) return l;
     if (r2==NULL) r2 = newnode();
     if (r1==NULL) r1 = newnode();
     int cnt = getSize(r2->ch[0])- getSize(r1->ch[0]);
     int m = (l+r)/2;
     if (k<=cnt)
        return query(l,m,r1->ch[0], r2->ch[0], k); else
        return query(m+1,r,r1->ch[1], r2->ch[1] , k-cnt);
}
void work()
{
     scanf("%d%d",&n,&m);
     for (int i = 1; i <= n;++i){
         scanf("%d",&a[i]);
         p[i].v = a[i]; p[i].id = i;
     }
     sort(p+1,p+n+1);
     a[p[1].id] = t = 1;num[1] = p[1].v;
     for (int i = 2; i <= n;++i)
     {
         t += (p[i].v != p[i-1].v);
         a[p[i].id] = t;
         num[t] = p[i].v; 
     }
     total = 0;
     root[0] = newnode();
     for (int i = 1; i <= n;++i)
         root[i] = update(1,t,root[i-1],a[i]);
     for (int i = 1; i <= m; ++i)
     {
         scanf("%d %d %d", &L, &R, &k);
         printf("%d\n",num[query(1,t,root[L-1],root[R],k)]);
     }
     //for (int i = 0; i < total;++i) delete &N[i];
}
int main()
{

    int test; cin>>test;
    while (test--){
          work();
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值