AvlTree,已测hdu 4006
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define Max_N 1000100
#define _max(a,b) ((a)>(b)?(a):(b))
#define size(_) ((_)==NULL ? 0 : (_)->size)
#define Height(_) ((_)==NULL ? -1 : (_)->Height)
typedef struct _avl{
int key, size, Height;
struct _avl *ch[2];
}AvlTree, *Avl;
AvlTree stack[Max_N];
int sz = 0;
void update(Avl x){
if (x == NULL) return;
x->size = size(x->ch[0]) + size(x->ch[1]) + 1;
x->Height = _max(Height(x->ch[0]), Height(x->ch[1])) + 1;
}
void rotate(Avl *x, int d){
Avl k = (*x)->ch[!d];
(*x)->ch[!d] = k->ch[d];
k->ch[d] = *x;
update(*x);
update(k);
*x = k;
}
void Maintain(Avl *x, int d){
if (Height((*x)->ch[d]) - Height((*x)->ch[!d]) == 2){
if (Height((*x)->ch[d]->ch[d]) - Height((*x)->ch[d]->ch[!d]) == 1){
rotate(x, !d);
} else if (Height((*x)->ch[d]->ch[d]) - Height((*x)->ch[d]->ch[!d]) == -1){
rotate(&((*x)->ch[d]), d), rotate(x, !d);
}
}
}
void insert(Avl *x, int key){
if (*x == NULL){
*x = &stack[sz++];
(*x)->ch[0] = (*x)->ch[1] = NULL;
(*x)->Height = 0, (*x)->key = key, (*x)->size = 1;
} else {
int d = key > (*x)->key;
insert(&((*x)->ch[d]), key);
update(*x);
Maintain(x, d);
}
}
int find_kth(Avl x, int k){
int t = 0;
for (;;){
t = size(x->ch[0]);
if (k == t + 1) break;
else if (k <= t) x = x->ch[0];
else k -= t + 1, x = x->ch[1];
}
return x->key;
}
int main(){
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w+", stdout);
#endif
char ch;
int i, n, k, d;
Avl 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;
}