hdu 4006 The kth great number

原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=4006
最近在看splay各种不顺,水一发冲一冲郁闷的心情,/(ㄒoㄒ)/~~

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define Max_N 1000010
#define size(_) ((_)==NULL ? 0 : (_)->size)
#define _size(_) (size((_)->ch[0]) + size((_)->ch[1]) + (_)->cnt)
typedef struct _treap{
    int val, fix, cnt, size;
    struct _treap *ch[2];
}treap, *Treap;
treap stack[Max_N];
int sz;
int run(){
    static int x = 1840828537;
    x += (x << 2) | 1;
    return x;
}
void rotate(Treap *x, int d){
    Treap k = (*x)->ch[!d];
    (*x)->ch[!d] = k->ch[d];
    k->ch[d] = *x;
    k->size = (*x)->size;
    (*x)->size = _size(*x);
    *x = k;
}
void insert(Treap *x, int val){
    int d = 0;
    if (*x == NULL){
        *x = &stack[sz++];
        (*x)->ch[0] = (*x)->ch[1] = NULL;
        (*x)->size = (*x)->cnt = 1, (*x)->val = val, (*x)->fix = run();
    } else if (val != (*x)->val){
        d = val > (*x)->val;
        insert(&((*x)->ch[d]), val);
        if ((*x)->ch[d]->fix < (*x)->fix) rotate(x, !d);
        (*x)->size = _size(*x);
    } else {
        (*x)->cnt++, (*x)->size++;
    }
}
int find_kth(Treap x, int k){
    int t = 0;
    for (; x != NULL;){
        t = size(x->ch[0]);
        if (t + 1 <= k && k <= t + x->cnt) break;
        if (k <= t) x = x->ch[0];
        else k -= t + x->cnt, 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;
    Treap 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、付费专栏及课程。

余额充值