排名算法

#include<stdio.h>

#include<iostream>
using namespace std;

struct BinaryTree
{
	int count;// 该节点的孩子总数
	int from_score;
	int to_score;
	BinaryTree* left;
	BinaryTree* right;
	BinaryTree(int from,int to,int c = 0):from_score(from),to_score(to),count(c),left(NULL),right(NULL){}
};

BinaryTree* createTree(BinaryTree*& root,int from,int to)
{
	if(from > to)return NULL;
	root = new BinaryTree(from,to);
	if(from == to)return root;
	int mid = from + ((to - from) >> 1);
	root -> left = createTree(root->left,from,mid);
	root -> right = createTree(root->right,mid+1,to);
	return root;
}

void insertNewScore(BinaryTree* root,int score)
{
	if(root == NULL)return;
	if(score >= root->from_score && score <= root->to_score)
		(root -> count) ++;
	int mid = root->from_score + ((root->to_score-root->from_score) >> 1);
	if(score <= mid)
		insertNewScore(root -> left,score);
	else 
		insertNewScore(root->right,score);
}

void deleteOldScore(BinaryTree* root,int score)
{
	if(root == NULL)return;
	if(score >= root->from_score && score <= root->to_score)
		(root -> count) --;
	int mid = root->from_score + ((root->to_score-root->from_score) >> 1);
	if(score <= mid)
		deleteOldScore(root -> left,score);
	else 
		deleteOldScore(root->right,score);
}

/* 更改score */
void changeScore(BinaryTree* root,int oldScore,int newScore)
{
	deleteOldScore(root,oldScore);
	insertNewScore(root,newScore);
}

void getRank(BinaryTree* root,int score,int& rank)
{
	if(root == NULL)return;
	int mid = root->from_score + ((root->to_score-root->from_score) >> 1);
	if(score > mid)getRank(root->right,score,rank);
	else if(root -> right)
	{
		rank += root -> right -> count;
		getRank(root->left,score,rank);
	}
}
int getRank(BinaryTree* root,int score)
{
	int rank = 1;
	getRank(root,score,rank);
	return rank;
}

void print(BinaryTree* root)
{
	if(root)
	{
		print(root -> left);
		cout << root -> from_score << "  " << root -> to_score << "  " << root -> count << endl;
		print(root -> right);
	}
}

int main()
{
	BinaryTree* root = NULL;
	createTree(root,1,10);//建立排名树
	int score[10] = {1,3,5,6,2,4,3,1,7,7};
	for(int i = 0;i < 10;i++)insertNewScore(root,score[i]);
	cout << "------------初始化后----------------" << endl;
	print(root);
	cout << "------------5的排名-----------------" << endl;
	cout << getRank(root,5) << endl;
	cout << "------------改变score----------------" << endl;
	changeScore(root,2,4);
	print(root);
	cout << "-------------3的排名----------------" << endl;
	cout << getRank(root,3) << endl;
}

 

posted on 2014-11-09 23:58  kangbry  阅读(130)  评论(0编辑  收藏  举报

导航