hdu 4006 AvlTree

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值