hdu 4006 The kth great number/SBT

原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=4006
这题原先用treap写过的,现在看了sb树。。本来想练习一下sbt树重复元素的插入,
搞了半天跟以前写的treap方法完全不一样/(ㄒoㄒ)/~~,
照下面的写法重复的节点被完全插入到树中了,o(╯□╰)o。。
如果重复元素很多,那会浪费太多的空间,不知到有没啥好的方法。。。
还是再慢慢想想吧,T_T…

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define Max_N 1000100
#define size(_) ((_)==NULL ? 0 : (_)->size)
typedef struct sbt{
    int val, size;
    struct sbt *ch[2];
}SBTNode, *SBT;
SBTNode stack[Max_N];
int sz = 0;
void rotate(SBT *x, int d){
    SBT k = (*x)->ch[!d];
    (*x)->ch[!d] = k->ch[d];
    k->ch[d] = *x;
    k->size = (*x)->size;
    (*x)->size = size((*x)->ch[0]) + size((*x)->ch[1]) + 1;
    (*x) = k;
}
void Maintain(SBT *x, int d){
    if ((*x)->ch[d] == NULL) return;
    if (size((*x)->ch[d]->ch[d]) > size((*x)->ch[!d])) rotate(x, !d);
    else if (size((*x)->ch[d]->ch[!d]) > size((*x)->ch[!d])){
        rotate(&((*x)->ch[d]), d), rotate(x, !d);
    } else {
        return;
    }
    Maintain(&((*x)->ch[0]), 0);
    Maintain(&((*x)->ch[1]), 1);
    Maintain(x, 0);
    Maintain(x, 1);
}
void insert(SBT *x, int val){
    int d = 0;
    if (*x == NULL){
        *x = &stack[sz++];
        (*x)->ch[0] = (*x)->ch[1] = NULL;
        (*x)->val = val, (*x)->size = 1;
    } else {
        d = val > (*x)->val;
        (*x)->size++;
        insert(&((*x)->ch[d]), val);
        Maintain(x, d);
    }
}
int find_kth(SBT x, int k){
    int t = 0;
    for (; x != NULL;){
        t = size(x->ch[0]);
        if (t + 1 == k) break;
        else if (k <= t) x = x->ch[0];
        else k -= t + 1, x = x->ch[1];
    }
    return  x->val;
}
int main(){
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w+", stdout);
#endif
    char ch;
    int i, n, k, d;
    SBT root = NULL;
    while (~scanf("%d %d", &n, &k)){
        sz = 0, root = NULL;
        for (i = 0; i < n; i++){
            getchar();
            scanf("%c", &ch);
            if ('I' == ch) scanf("%d", &d), insert(&root, d);
            else printf("%d\n", find_kth(root, root->size - k + 1));
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值