Sum of Manhattan distances between repetitions in a String | C ++ program for the above approach ; Function to find the sum of the manhattan distances between same characters in string ; Vector to store indices for each unique character of the string ; Append the position of each character in their respective vectors ; Store the required result ; Iterate over all the characters ; Calculate sum of all elements present in the vector ; Traverse the current vector ; Find suffix [ i + 1 ] ; Adding distance of all pairs whose first element is i and second element belongs to [ i + 1 , n ] ; Print the result ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void SumofDistances ( string s ) { vector < int > v [ 26 ] ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { v [ s [ i ] - ' a ' ] . push_back ( i ) ; } int ans = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { int sum = 0 ; for ( int j = 0 ; j < v [ i ] . size ( ) ; j ++ ) { sum += v [ i ] [ j ] ; } for ( int j = 0 ; j < v [ i ] . size ( ) ; j ++ ) { sum -= v [ i ] [ j ] ; ans += ( sum - ( v [ i ] . size ( ) - 1 - j ) * ( v [ i ] [ j ] ) ) ; } } cout << ans ; } int main ( ) { string s = " ababa " ; SumofDistances ( s ) ; return 0 ; }