POJ 2761可以练习无数种数据结构的题——动态区间求第K小

Teap:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
const int maxn=100010;
using namespace std;
struct node{
    node *ch[2];
    int v,r,s;
    int cmp(int x)const{
        if(x==v) return -1;
        return x<v ? 0:1;
    }
    void push_up(){
        s=1;
        if(ch[0]!=NULL) s+=ch[0]->s;
        if(ch[1]!=NULL) s+=ch[1]->s;
    }
};
node* root;
inline void rotate(node* &o,int d)
{
    node* k=o->ch[d^1];
    o->ch[d^1]=k->ch[d];
    k->ch[d]=o;
    o->push_up();
    k->push_up();
    o=k;
}
inline void insert(node* &o,int x)
{
    if(o==NULL){
        o=new node();
        o->ch[0]=o->ch[1]=NULL;
        o->v=x;
        o->r=rand();
    }else{
        int d=o->cmp(x);
        cout<<"d="<<d<<endl;
        insert(o->ch[d],x);
        if(o->ch[d]->r >o->r) rotate(o,d^1);
    }
    o->push_up();
}
inline void remove(node* &o,int x)
{
    if(o==NULL) return;
    int d=((x<o->v)?0:1);
    if(o->v==x){
        if(o->ch[0]==NULL) o=o->ch[1];
        else if(o->ch[1]==NULL) o=o->ch[0];
        else{
            int d2=(o->ch[0]->r > o->ch[1]->r?1:0);
            rotate(o,d2);remove(o->ch[d2],x);
        }
    }else remove(o->ch[d],x);
    if(o!=NULL) o->push_up();
}
int select(node *o,int k)
{
    int s=(o->ch[0]==NULL ?0:o->ch[0]->s);
    if(k==s+1) return o->v;
    else if(k<=s) return select(o->ch[0],k);
    else return select(o->ch[1],k-s-1);
}
struct pp{
    int l,r,k,id;
    bool operator<(pp x)const{
        return l<x.l;
    }
}que[maxn];
int n,m,num[maxn],ans[maxn];
int main()
{
    while(scanf("%d%d",&n,&m)!=EOF){
        root=NULL;
        for(int i=1;i<=n;++i) scanf("%d",&num[i]);
        for(int i=0;i<m;++i){
            scanf("%d%d%d",&que[i].l,&que[i].r,&que[i].k);
            que[i].id=i;
        }
        sort(que,que+m);
        int l=que[0].l,r=que[0].l;
        for(int i=0;i<m;++i){
            while(l<que[i].l){
                remove(root,num[l]);
                l++;
            }
            while(r<=que[i].r){
                insert(root,num[r]);
                r++;
            }
            ans[que[i].id]=select(root,que[i].k);
        }
        for(int i=0;i<m;++i){
            printf("%d\n",ans[i]);
        }
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值