Rearrange an Array such that Sum of same | C ++ Program to implement the above approach ; Function to rearrange the array such that no same - indexed subset have sum equal to that in the original array ; Initialize a vector ; Iterate the array ; Sort the vector ; Shift of elements to the index of its next cyclic element ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printNewArray ( vector < int > a , int n ) { vector < pair < int , int > > v ; for ( int i = 0 ; i < n ; i ++ ) { v . push_back ( { a [ i ] , i } ) ; } sort ( v . begin ( ) , v . end ( ) ) ; int ans [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { ans [ v [ ( i + 1 ) % n ] . second ] = v [ i ] . first ; } for ( int i = 0 ; i < n ; i ++ ) { cout << ans [ i ] << " ▁ " ; } } int main ( ) { vector < int > a = { 4 , 1 , 2 , 5 , 3 } ; int n = a . size ( ) ; printNewArray ( a , n ) ; return 0 ; }