-
Notifications
You must be signed in to change notification settings - Fork 0
/
order_statics_tree_using_BIT.cpp
72 lines (56 loc) · 1.12 KB
/
order_statics_tree_using_BIT.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include<iostream>
#include<vector>
using namespace std;
const int MAX_VAL=1000001;
void update_bit(int i, int add, vector<int> &bit){
while(i>0 && i<bit.size()){
bit[i]+=add;
i+= i & (-i);
}
}
int get_sum(int i, vector<int> &bit){
int sum=0;
while(i>0){
sum+=bit[i];
i-= i &(-i);
}
return sum;
}
int find_kth_smallest_element(int k, vector<int> &bit){
int l=0;
int h=bit.size();
while(l<h){
int mid=(l+h)/2;
if(k<=get_sum(mid, bit)){
h=mid;
}
else{
l=mid+1;
}
}
return l;
}
void insert_element(int x, vector<int> &bit){
update_bit(x, 1, bit);
}
void delete_element(int x, vector<int> &bit){
update_bit(x, -1, bit);
}
int find_rank(int x, vector<int> &bit){
return get_sum(x, bit);
}
int main(){
vector<int> BIT(MAX_VAL);
insert_element(20, BIT);
insert_element(50, BIT);
insert_element(30, BIT);
insert_element(40, BIT);
cout << "2nd Smallest element is "
<< find_kth_smallest_element(2, BIT) << endl;
cout << "Rank of 40 is "
<< find_rank(40, BIT) << endl;
delete_element(40, BIT);
cout << "Rank of 50 is "
<< find_rank(50, BIT) << endl;
return 0;
}