C++ code to find the area taken by boxes in a container


Suppose, we have n pairs of boxes that need to be shipped in a square-shaped container. The width of the pair of the boxes is given as a pair (a, b) and they are given in an array 'dimensions'. If we keep the width of the boxes parallel to each other, we have to find out how much area the boxes will take inside the container. We cannot stack the boxes on top of each other. We determine the minimum area required by the two boxes in the container for all the n pairs.

So, if the input is like n = 4, dimensions = {{2, 4}, {3, 6}, {2, 5}, {4, 6}}, then the output will be −

64
25
36
16

Steps

To solve this, we will follow these steps −

res := 0
while n is non-zero, do:
   a := first value of dimensions[n]
   b := second value of dimensions[n]
   res := maximum of (2 * minimum of (a, b) and maximum of a and b)
   print(res * res)
   n := n - 1

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
#define N 100
void solve(int n, vector<pair<int, int>> dimensions) {
   int res = 0;
   while(n--){
      int a = dimensions[n].first;
      int b = dimensions[n].second;
      int res = max(2 * min(a, b), max(a, b));
      cout<< res * res << endl;
   }
}
int main() {
   int n = 4;
   vector<pair<int, int>> dimensions = {{2, 4}, {3, 6}, {2, 5}, {4, 6}};
   solve(n, dimensions);
   return 0;
}

Input

4, {{2, 4}, {3, 6}, {2, 5}, {4, 6}}

Output

64
25
36
16

Updated on: 11-Mar-2022

128 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements