Array sum after replacing all occurrences of X by Y for Q queries | C ++ implementation to find the sum of the array for the given Q queries ; Function that print the sum of the array for Q queries ; Stores the frequencies of array elements ; Calculate the sum of the initial array and store the frequency of each element in map ; Iterate for all the queries ; Store query values ; Decrement the sum accordingly ; Increment the sum accordingly ; Set count of Y [ i ] ; Reset count of X [ i ] ; Print the sum ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sumOfTheArrayForQuery ( int * A , int N , int * X , int * Y , int Q ) { int sum = 0 ; unordered_map < int , int > count ; for ( int i = 0 ; i < N ; i ++ ) { sum += A [ i ] ; count [ A [ i ] ] ++ ; } for ( int i = 0 ; i < Q ; i ++ ) { int x = X [ i ] , y = Y [ i ] ; sum -= count [ X [ i ] ] * X [ i ] ; sum += count [ X [ i ] ] * Y [ i ] ; count [ Y [ i ] ] += count [ X [ i ] ] ; count [ X [ i ] ] = 0 ; cout << sum << " ▁ " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 1 , 3 , 2 } ; int X [ ] = { 2 , 3 , 5 } ; int Y [ ] = { 3 , 1 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int Q = sizeof ( X ) / sizeof ( X [ 0 ] ) ; sumOfTheArrayForQuery ( arr , N , X , Y , Q ) ; return 0 ; }