Find sum of product of every number and its frequency in given range | C ++ implementation to find sum of product of every number and square of its frequency in the given range ; Function to solve queries ; Calculating answer for every query ; The end points of the ith query ; map for storing frequency ; Incrementing the frequency ; Iterating over map to find answer ; adding the contribution of ith number ; print answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void answerQueries ( int arr [ ] , int n , vector < pair < int , int > > & queries ) { for ( int i = 0 ; i < queries . size ( ) ; i ++ ) { int ans = 0 ; int l = queries [ i ] . first - 1 ; int r = queries [ i ] . second - 1 ; map < int , int > freq ; for ( int j = l ; j <= r ; j ++ ) { freq [ arr [ j ] ] ++ ; } for ( auto & i : freq ) { ans += ( i . first * i . second ) ; } cout << ans << endl ; } } int main ( ) { int arr [ ] = { 1 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; vector < pair < int , int > > queries = { { 1 , 2 } , { 1 , 3 } } ; answerQueries ( arr , n , queries ) ; }