Sort the indices based on their corresponding value in V
vector < pair < int , pair < int , int > > > vec ; for ( int i = 0 ; i < n ; i ++ ) { vec . push_back ( { v [ i ] . first , { v [ i ] . second , i } } ) ; } sort ( vec . begin ( ) , vec . end ( ) ) ;