动态询问一些数中第k大的数(没有删除操作)。为了学习AVL树,用AVL码的,居然1A了,但是效率并不比普通二叉树有所提高。做法是在AVL树的基础上,维护每个节点的大小,根据大小信息查找第k大。
#include <iostream>
#include <stdio.h>
#include <string>
#include <map>
#include <vector>
#include <stack>
#include <queue>
#include <string.h>
#include <algorithm>
#include <math.h>
using namespace std;
struct avl{
int data;
int height;
avl* pleft;
avl* pright;
int size;
};
int Height(avl* pNode){
if(NULL==pNode)return -1;
return pNode->height;
}
int Size(avl* pNode){
if(NULL==pNode)return 0;
return pNode->size;
}
avl* LLRotate(avl* pNode){
avl* l=pNode->pleft;
pNode->pleft=l->pright;
l->pright=pNode;
pNode->size=Size(pNode->pleft)+Size(pNode->pright)+1;
l->size=Size(l->pleft)+Size(l->pright)+1;
pNode->height=max(Height(pNode->pleft),Height(pNode->pright))+1;
l->height=max(Height(l->pleft),Height(l->pright))+1;
return l;
}
avl* RRRotate(avl* pNode){
avl* r=pNode->pright;
pNode->pright=r->pleft;
r->pleft=pNode;
pNode->size=Size(pNode->pleft)+Size(pNode->pright)+1;
r->size=Size(r->pleft)+Size(r->pright)+1;
pNode->height=max(Height(pNode->pleft),Height(pNode->pright))+1;
r->height=max(Height(r->pleft),Height(r->pright))+1;
return r;
}
avl* LRRotate(avl* pNode){
pNode->pleft=RRRotate(pNode->pleft);
return LLRotate(pNode);
}
avl* RLRotate(avl* pNode){
pNode->pright=LLRotate(pNode->pright);
return RRRotate(pNode);
}
avl* insert(avl* pNode,int data){
if(pNode==NULL){
pNode=new avl();
pNode->data=data;
pNode->height=0;
pNode->size=1;
}else if(data>pNode->data){
pNode->pleft=insert(pNode->pleft,data);
pNode->size++;
if(Height(pNode->pleft)-Height(pNode->pright)==2){ //不平衡
if(data>pNode->pleft->data){
pNode=LLRotate(pNode);
}else{
pNode=LRRotate(pNode);
}
}
}else{
pNode->pright=insert(pNode->pright,data);
pNode->size++;
if(Height(pNode->pright)-Height(pNode->pleft)==2){ //不平衡
if(data<pNode->pright->data){
pNode=RRRotate(pNode);
}else{
pNode=RLRotate(pNode);
}
}
}
pNode->height=max(Height(pNode->pleft),Height(pNode->pright));
return pNode;
}
int query(avl* pNode,int q){
int lsiz=0;
if(pNode->pleft)lsiz=pNode->pleft->size;
int rsiz=0;
if(pNode->pright)rsiz=pNode->pright->size;
if(lsiz+1==q) return pNode->data;
else if(lsiz>=q) return query(pNode->pleft,q);
else return query(pNode->pright,q-1-lsiz);
}
int main(){
int n,k;
while(cin>>n>>k){
avl* root=NULL;
for(int i=1;i<=n;i++){
char op[2];
scanf("%s",op);
if(op[0]=='I'){
int num;
scanf("%d",&num);
root=insert(root,num);
}else{
int ans=query(root,k);
printf("%d\n",ans);
}
}
}
return 0;
}