Range queries for alternatively addition and subtraction on given Array | C ++ program for the above approach ; Structure to represent a range query ; Function to find the result of alternatively adding and subtracting elements in the range [ L , R ] ; A boolean variable flag to alternatively add and subtract ; Iterate from [ L , R ] ; if flag is false , then add & toggle the flag ; if flag is true subtract and toggle the flag ; Return the final result ; Function to find the value for each query ; Iterate for each query ; Driver Code ; Given array ; Given Queries ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Query { int L , R ; } ; int findResultUtil ( int arr [ ] , int L , int R ) { int result = 0 ; bool flag = false ; for ( int i = L ; i <= R ; i ++ ) { if ( flag == false ) { result = result + arr [ i ] ; flag = true ; } else { result = result - arr [ i ] ; flag = false ; } } return result ; } void findResult ( int arr [ ] , int n , Query q [ ] , int m ) { for ( int i = 0 ; i < m ; i ++ ) { cout << findResultUtil ( arr , q [ i ] . L , q [ i ] . R ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 10 , 13 , 15 , 2 , 45 , 31 , 22 , 3 , 27 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Query q [ ] = { { 2 , 5 } , { 6 , 8 } , { 1 , 7 } , { 4 , 8 } , { 0 , 5 } } ; int m = sizeof ( q ) / sizeof ( q [ 0 ] ) ; findResult ( arr , n , q , m ) ; return 0 ; }