Multiplication on Array : Range update query in O ( 1 ) | C ++ program for the above approach ; Creates a mul [ ] array for A [ ] and returns it after filling initial values . ; Does range update ; Prints updated Array ; Driver code ; ; Array to be updated ; Create and fill mul and div Array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void initialize ( int mul [ ] , int div [ ] , int size ) { for ( int i = 1 ; i < size ; i ++ ) { mul [ i ] = ( mul [ i ] * mul [ i - 1 ] ) / div [ i ] ; } } void update ( int l , int r , int x , int mul [ ] , int div [ ] ) { mul [ l ] *= x ; div [ r + 1 ] *= x ; } void printArray ( int ar [ ] , int mul [ ] , int div [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { ar [ i ] = ar [ i ] * mul [ i ] ; cout << ar [ i ] << " ▁ " ; } } int main ( ) { int ar [ ] = { 10 , 5 , 20 , 40 } ; int n = sizeof ( ar ) / sizeof ( ar [ 0 ] ) ; int mul [ n + 1 ] , div [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) { mul [ i ] = div [ i ] = 1 ; } update ( 0 , 1 , 10 , mul , div ) ; update ( 1 , 3 , 20 , mul , div ) ; update ( 2 , 2 , 2 , mul , div ) ; initialize ( mul , div , n + 1 ) ; printArray ( ar , mul , div , n ) ; return 0 ; }