Find the distance between two person after reconstruction of queue | C ++ implementation of the approach ; Function to find the correct order and then return the distance between the two persons ; Make pair of both height & infront and insert to vector ; Sort the vector in ascending order ; Find the correct place for every person ; Insert into position vector according to infront value ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getDistance ( int arr [ ] [ 2 ] , int n , int a , int b ) { vector < pair < int , int > > vp ; for ( int i = 0 ; i < n ; i ++ ) { vp . push_back ( { arr [ i ] [ 0 ] , arr [ i ] [ 1 ] } ) ; } sort ( vp . begin ( ) , vp . end ( ) ) ; vector < int > pos ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) { int height = vp [ i ] . first ; int k = vp [ i ] . second ; pos . insert ( pos . begin ( ) + k , height ) ; } int first = -1 , second = -1 ; for ( int i = 0 ; i < pos . size ( ) ; i ++ ) { if ( pos [ i ] == a ) first = i ; if ( pos [ i ] == b ) second = i ; } return abs ( first - second ) ; } int main ( ) { int arr [ ] [ 2 ] = { { 5 , 0 } , { 3 , 0 } , { 2 , 0 } , { 6 , 4 } , { 1 , 0 } , { 4 , 3 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int a = 6 , b = 5 ; cout << getDistance ( arr , n , a , b ) ; return 0 ; }