这个是动态统计量的一个思路,下面我实现的是静态的统计量的一个demo,没有考虑动态的添加和删除元素。
基本思路:对数组中的每一个元素建立一颗二叉排序树,对树种的每个节点添加一个count,记录包含它在内的子孩子个数。在查找时就可以递归的进行查找了:
代码:
#include<iostream>
using namespace std;
struct Node{
int value;
int count;
Node *left,*right;
};
void build(Node*& root,int val){
if(root==NULL){
root=new Node();
root->value=val;
return ;
}
if(val<root->value)
build(root->left,val);
else
build(root->right,val);
}
void update(Node* root){
if(root==NULL)
return ;
if(root!=NULL&&root->left==NULL&&root->right==NULL)
root->count=1;
int t=0;
if(root->left!=NULL)
{update(root->left);t+=root->left->count;}
if(root->right!=NULL)
{update(root->right);t+=root->right->count;}
root->count=t+1;
}
void deleteTree(Node* root){
if(root->left!=NULL)
deleteTree(root->left);
if(root->right!=NULL)
deleteTree(root->right);
delete(root);
}
int osRank(Node* root,int x){
if(NULL==root)
return -1;
int r=1;
if(root->left!=NULL)
r+=root->left->count;
if(x==r)
return root->value;
else if(x<r)
return osRank(root->left,x);
else return osRank(root->right,x-r);
}
int main(){
int a[5]={4,1,5,2,6};
Node* root=NULL;
for(int i=0;i<sizeof(a)/sizeof(a[0]);++i)
build(root,a[i]);
update(root);
cout<<osRank(root,5)<<endl;
if(root!=NULL)
deleteTree(root);
system("pause");
return 0;
}