Calculate cost of visiting all array elements in increasing order | C ++ implementation of the above approach ; Function to calculate total cost of visiting array elements in increasing order ; Stores the pair of element and their positions ; Traverse the array arr [ ] ; Push the pair { arr [ i ] , i } in v ; Sort the vector in ascending order . ; Stores the total cost ; Stores the index of last element visited ; Traverse the vector v ; Increment ans ; Assign ; Return ans ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateDistance ( int arr [ ] , int N ) { vector < pair < int , int > > v ; for ( int i = 0 ; i < N ; i ++ ) v . push_back ( { arr [ i ] , i } ) ; sort ( v . begin ( ) , v . end ( ) ) ; int ans = 0 ; int last = 0 ; for ( auto j : v ) { ans += abs ( j . second - last ) ; last = j . second ; } return ans ; } int main ( ) { int arr [ ] = { 4 , 3 , 2 , 5 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << calculateDistance ( arr , N ) ; }