//
// main.cpp
// Segment Tree
//
// Created by Himanshu on 22/08/21.
//
#include <iostream>
#include <math.h>
using namespace std;
const int N = 6 ;
int seg[ 2 * N- 1 ] ;
int construct ( int arr[ ] , int sb, int se, int si) {
if ( sb == se) {
seg[ si] = arr[ sb] ;
} else {
int mid = ( sb + se) / 2 ;
seg[ si] = construct( arr, sb, mid, 2 * si + 1 ) +
construct( arr, mid+ 1 , se, 2 * si + 2 ) ;
}
return seg[ si] ;
}
int getSum( int sb, int se, int x, int y, int i) {
if ( sb > y || se < x) {
return 0 ;
} else if ( sb >= x && se <= y) {
return seg[ i] ;
} else {
int mid = ( sb+ se) / 2 ;
return getSum( sb, mid, x, y, 2 * i + 1 ) + getSum( mid+ 1 , se, x, y, 2 * i + 2 ) ;
}
}
void update ( int sb, int se, int idx, int diff, int i) {
if ( idx < sb || idx > se) {
return ;
}
seg[ i] + = diff;
if ( sb ! = se) {
int mid = ( sb+ se) / 2 ;
update( sb, mid, idx, diff, ( 2 * i + 1 ) ) ;
update( mid+ 1 , se, idx, diff, ( 2 * i + 2 ) ) ;
}
}
int main( ) {
int arr[ ] = { 1 , 3 , 2 , 7 , 9 , 11 } ;
// Constructing segment tree (preprocessing)
construct( arr, 0 , N- 1 , 0 ) ;
// Print minimum value in arr[qs..qe]
cout << "Sum in the range:" << endl;
cout << "x = 0, y = 2: " << getSum( 0 , N- 1 , 0 , 2 , 0 ) << endl;
cout << "x = 3, y = 4: " << getSum( 0 , N- 1 , 3 , 4 , 0 ) << endl;
cout << "Update index 3, from 7 to 1" << endl;
int diff = 1 - arr[ 3 ] ;
update( 0 , N- 1 , 3 , diff, 0 ) ;
cout << "x = 2, y = 5: " << getSum( 0 , N- 1 , 2 , 5 , 0 ) << endl;
cout << "Update index 5, from 11 to 2" << endl;
diff = 2 - arr[ 5 ] ;
update( 0 , N- 1 , 5 , diff, 0 ) ;
cout << "x = 3, y = 5: " << getSum( 0 , N- 1 , 3 , 5 , 0 ) << endl;
cout << "x = 0, y = 5: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