-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFenwickTree.cpp
More file actions
executable file
·96 lines (76 loc) · 2.01 KB
/
FenwickTree.cpp
File metadata and controls
executable file
·96 lines (76 loc) · 2.01 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include<bits/stdc++.h>
using namespace std ;
void update(int index , int value , int *BIT, int n){
for(; index <= n ; index += index&(-index)){
BIT[index] += value ;
}
}
int query(int index , int *BIT){
int sum = 0 ;
for(; index>0 ; index -= index&(-index)){
sum += BIT[index];
}
return sum ;
}
int main(){
int n ;
cout << "Enter the size of the array" <<endl;
cin >> n ;
int *arr = new int[n+1] ;
int *BIT = new int[n+1] ;
for(int i=1 ; i <= n ; i++){
arr[i] = 0 ;
BIT[i] = 0 ;
}
//Input
for(int i =1 ; i<= n ; i++){
cin >> arr[i] ;
update(i , arr[i] , BIT ,n) ;
}
//display
cout << "The array is\t" ;
for(int i=1 ; i <=n ; i++){
cout << arr[i] << " " ;
}
int si ,ei;
//QUERY 1
cout << "Enter the starting index \t" ;
cin >> si ;
if(si <1 || si > n){
cout << "Out of range index. Enter again\t";
cin >> si ;
}
cout << "Enter the ending index\t" ;
cin >> ei ;
if(ei > n || ei <si){
cout << "Out of range index.Enter again\t" ;
cin >> ei ;
}
cout << "Sum of array from index " << si << " to " << ei << "is\t" << query(ei,BIT)-query(si-1,BIT) << endl;
//UPDATE
int ind;
cout << "Enter the index which has to be updated\t" ;
cin >> ind ;
cout << "Enter the new value\t" ;
int val ;
cin >> val ;
update(ind , val -arr[ind], BIT , n) ;
arr[ind] = val ;
cout << "The array is\t" ;
for(int i=1 ; i <=n ; i++){
cout << arr[i] << " " ;
}
cout << "Enter the starting index \t" ;
cin >> si ;
if(si <1 || si > n){
cout << "Out of range index. Enter again\t";
cin >> si ;
}
cout << "Enter the ending index\t" ;
cin >> ei ;
if(ei > n || ei <si){
cout << "Out of range index.Enter again\t" ;
cin >> ei ;
}
cout << "Sum of array from index " << si << " to " << ei << "is\t" << query(ei,BIT)-query(si-1,BIT) << endl;
}