Perform range sum queries on string as per given condition | C ++ program for the above approach ; Function to perform range sum queries on string as per the given condition ; Initialize N by string size ; Create array A [ ] for prefix sum ; Iterate till N ; Traverse the queries ; Check if if L == 1 range sum will be A [ R - 1 ] ; Condition if L > 1 range sum will be A [ R - 1 ] - A [ L - 2 ] ; Driver Code ; Given string ; Given Queries ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Range_sum_query ( string S , vector < pair < int , int > > Query ) { int N = S . length ( ) ; int A [ N ] ; A [ 0 ] = S [ 0 ] - ' a ' + 1 ; for ( int i = 1 ; i < N ; i ++ ) { A [ i ] = S [ i ] - ' a ' + 1 ; A [ i ] = A [ i ] + A [ i - 1 ] ; } for ( int i = 0 ; i < Query . size ( ) ; i ++ ) { if ( Query [ i ] . first == 1 ) { cout << A [ ( Query [ i ] . second ) - 1 ] << endl ; } else { cout << A [ ( Query [ i ] . second ) - 1 ] - A [ ( Query [ i ] . first ) - 2 ] << endl ; } } } int main ( ) { string S = " abcd " ; vector < pair < int , int > > Query ; Query . push_back ( make_pair ( 2 , 4 ) ) ; Query . push_back ( make_pair ( 1 , 3 ) ) ; Range_sum_query ( S , Query ) ; return 0 ; }