# Find the minimum number of rectangles left after inserting one into another in C++

C++Server Side ProgrammingProgramming

Suppose we have width and height of N different rectangles; we have to find the minimum number of rectangles left after inserting one into another. So, if W1 and W2 be the width of rectangles R1 and R2 respectively. And H1 and H2 be the height of R1 and R2 respectively, then if W1 < W2 and H1 < H2 then rectangle R1 fits inside rectangle R2. Thus, the smallest one can fit into second smallest, then that fits into the next and so on.

So, if the input is like {{ 30, 45 }, { 15, 15 }, { 45, 30 },{60, 75 }}, then the output will be 2 as one of the possible ways is to insert second rectangle into the first one and then insert that rectangle into the fourth. The Third and fourth rectangles left.

To solve this, we will follow these steps −

• n := size of boxes

• sort the array boxes based on their size

• Define an array nested of pairs

• insert boxes[n - 1] at the end of nested

• for initialize i := n - 2, when i >= 0, update (decrease i by 1), do −

• right := size of nested

• while left <= right, do:

• mid := (right + left) / 2

• if height of nested[mid] is same as height of boxes[i] or width of nested[mid] <= width of boxes[i], then −

• left := mid + 1

• Otherwise

• right := mid - 1

• if left is same as size of nested, then −

• insert boxes[i] at the end of nested

• Otherwise

• width of nested[left] := width of boxes[i]

• height of nested[left] := height of boxes[i]

• return size of nested

## Example

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
bool comp(const pair<int, int>& L, const pair<int, int>& R) {
if (L.first == R.first)
return L.second > R.second;
return L.first < R.first;
}
int Rectangles(vector<pair<int, int>> &boxes) {
int n = boxes.size();
sort(boxes.begin(), boxes.end(), comp);
vector<pair<int, int< < nested;
nested.push_back(boxes[n - 1]);
for (int i = n - 2; i >= 0; --i) {
int right = nested.size() - 1, left = 0;
while (left <= right) {
int mid = (right + left) / 2;
if (nested[mid].first == boxes[i].first || nested[mid].second <= boxes[i].second)
left = mid + 1;
else
right = mid - 1;
}
if (left == nested.size())
nested.push_back(boxes[i]);
else {
nested[left].second = boxes[i].second;
nested[left].first = boxes[i].first;
}
}
return nested.size();
}
int main() {
vector<pair<int, int>> boxes = {{30, 45}, {15,15}, {45,30},{60,75}};
cout << Rectangles(boxes);
}

## Input

{{30, 45}, {15,15}, {45,30},{60,75}}

## Output

2