【treap tree】 HDOJ 4006

平衡树模板题。。考虑输入的数可能重复。。

#include <iostream>  
#include <queue>  
#include <stack>  
#include <map>  
#include <set>  
#include <bitset>  
#include <cstdio>  
#include <algorithm>  
#include <cstring>  
#include <climits>  
#include <cstdlib>
#include <cmath>
#define maxn 5005
#define eps 1e-10
#define mod 1000000009
#define INF 99999999  
#define lowbit(x) (x&(-x))  
//#define lson o<<1, L, mid  
//#define rson o<<1 | 1, mid+1, R  
typedef long long LL;
//typedef int LL;
using namespace std;

struct node
{
	int s, key, v, c;
	node *ch[2];
	void maintain(void) {
		s = ch[0]->s+ch[1]->s+c;
	}
	int cmp(int x) const {
		if(x == v) return -1;
		else return x < v ? 0 : 1;
	}
}*root, *null;
void init(void)
{
	null = new node();
	null->s = null->v = null->c = 0;
	root = new node();
	root = null;
}
void rotate(node* &o, int d)
{
	node *k = o->ch[d^1]; o->ch[d^1] = k->ch[d], k->ch[d] = o;
	o->maintain(), k->maintain(), o = k;
}
void insert(node* &o, int x)
{
	if(o == null) {
		o = new node();
		o->c = o->s = 1, o->v = x, o->key = rand();
		o->ch[0] = o->ch[1] = null;
		return;
	}
	int d = o->cmp(x);
	if(d == -1) o->c++;
	else {
		insert(o->ch[d], x);
		if(o->ch[d]->key > o->key) rotate(o, d^1);
	}
	o->maintain();
}
int find(node *o, int k)
{
	if(o->ch[1]->s >= k) return find(o->ch[1], k);
	if(o->ch[1]->s + o->c >=k) return o->v;
	return find(o->ch[0], k - o->c - o->ch[1]->s);
}
int main(void)
{
	char c[5];
	int n, k, x;
	while(scanf("%d%d", &n, &k)!=EOF) {
		init();
		while(n--) {
			scanf("%s", c);
			if(c[0] == 'I') scanf("%d", &x), insert(root, x);
			else printf("%d\n", find(root, k));
		}
	}
	return 0;
}


你可能感兴趣的:(HDU,treap)