Home  >  Article  >  Backend Development  >  C++ Program: Find the number of boxes visible after placing one box inside another box

C++ Program: Find the number of boxes visible after placing one box inside another box

王林
王林forward
2023-09-11 23:37:021247browse

C++ Program: Find the number of boxes visible after placing one box inside another box

To solve a problem, we are given an array containing the box dimensions. Now we have a condition, if the size of the big box is at least twice that of the small box, then we can put the small box into the big box. Now we have to determine how many visible boxes there are, for example.

Input : arr[] = { 1, 3, 4, 5 }
Output : 3
Put a box of size 1 in the box of size 3.

Input : arr[] = { 4, 2, 1, 8 }
Output : 1

Methods to find the solution

In this problem, our approach is to sort the array as we go. We now push the element into the queue. As we progress, we'll check if the current element is greater than or equal to twice the size of the element at the front of the queue. If true, we now pop the previous element. Finally, we push the current element into the queue. Our answer will be the size of the queue at the end.

Example

#include <bits/stdc++.h>
using namespace std;
int main(){
    int arr[] = { 1, 2, 3, 4, 5, 6 }; // given array containing the size of our boxes
    int n = sizeof(arr) / sizeof(arr[0]); // size of our array
    queue<int> q;
    sort(arr, arr + n); // sorting our array
    q.push(arr[0]); // pushing the smallest element in the front
    for (int i = 1; i < n; i++) { // traversing the array
        int curr = q.front(); // current element
        if (arr[i] >= 2 * curr) // if the size of the current box is greater than twice
                               // of the box in front so we pop the front
            q.pop();

        q.push(arr[i]); // pushing the current element in the queue
    }
    cout << q.size() << "\n"; // our answer
    return 0;
}

Output

3

Conclusion

In this tutorial we solved the problem of placing a box inside another box Then find the number of visible boxes. We also learned the C program for this problem and the complete method (general) to solve it. We can write the same program in other languages ​​such as C, java, python and other languages. We hope you found this tutorial helpful.

The above is the detailed content of C++ Program: Find the number of boxes visible after placing one box inside another box. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete