/* 11.8 Imagine you are reading in a stream of integers.
Periodically, you wish to
be able to look up the rank of a number x (the number of values less than or
equal to x).
Implement the data
structures and the algorithms to support these operations.
That is, implement the
method track(int x), which is called when each number is generated,
and the method
getRankOfNumber(int x), which returns the number of values less than or equal to
x (not including x itself). */
#include <iostream>
using namespace std;
struct node {
int value;
unsigned rank, mark;
node * left, *
right;
node();
};
class bstWithRank {
public:
bstWithRank();
~bstWithRank() { deletebst(head); }
void track(int);
unsigned
getRankOfNumber(int);
private:
void deletebst(node *);
node * head;
};
node::node(): value(0), rank(0), mark(0), left(nullptr), right(nullptr) {}
bstWithRank::bstWithRank(){
head = new node();
}
void bstWithRank::track(int x){
node * ptr = head;
unsigned rank = 0;
while (ptr->left != nullptr){
if (ptr->value < x){
rank = ptr->rank + 1;
ptr = ptr->right;
}
else{
++(ptr->rank);
++(ptr->right->mark);
ptr = ptr->left;
}
}
ptr->value = x;
ptr->rank = rank;
ptr->mark = 0;
ptr->left = new node();
ptr->right = new node();
}
unsigned bstWithRank::getRankOfNumber(int x){
node * ptr = head;
unsigned rank = 0;
while (ptr->left != nullptr){
if (ptr->mark > 0){
ptr->rank += ptr->mark;
ptr->left->mark += ptr->mark;
ptr->right->mark += ptr->mark;
ptr->mark = 0;
}
if (ptr->value == x)
return ptr->rank;
if (ptr->value < x) {
rank = ptr->rank+1;
ptr = ptr->right;
}
else {
ptr = ptr->left;
}
}
return rank;
}
void bstWithRank::deletebst(node * ptr){
if (ptr->left != nullptr) {
deletebst(ptr->left);
}
if (ptr->right != nullptr) {
deletebst(ptr->right);
}
delete ptr;
}
No comments:
Post a Comment