# Queue Reconstruction by Height in C++

C++Server Side ProgrammingProgramming

Consider we have a random list of people standing in a queue. If each person is described by a pair of integers (h, k), where h is the height and k is the number of people in front of him, who have a height greater than or equal to h. We have to define one method to reconstruct the queue. So if the given array is like [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]], then the output will be [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

To solve this, we will follow these steps −

• sort the given array based on the following comparison strategy
• if a = b, then return a > b, otherwise return a < b
• create one vector called ans
• for i in range size of given array down to 0
• insert (first element of ans + p[i, 1], p[i]) into ans array
• return ans

## Example

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
bool cmp(vector <int> a, vector <int> b){
if(a == b)return a > b;
return a < b;
}
class Solution {
public:
vector<vector<int>> reconstructQueue(vector<vector<int>>& p) {
sort(p.begin(), p.end(), cmp);
vector < vector <int> > ans;
for(int i = p.size()-1; i>=0; i--){
ans.insert(ans.begin() + p[i], p[i]);
}
return ans;
}
};
main(){
Solution ob;
vector<vector<int>> v = {{7,0}, {4,4}, {7,1}, {5,0}, {6,1}, {5,2}};
print_vector(ob.reconstructQueue(v));
}

## Input

[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

## Output

[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]