卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章19577本站已运行344

C++程序:找出将一个盒子放入另一个盒子后可见的盒子数量

C++程序:找出将一个盒子放入另一个盒子后可见的盒子数量

解决一个问题,我们给定一个包含盒子尺寸的数组。现在我们有一个条件,如果大盒子的尺寸至少是小盒子的两倍,那么我们可以把小盒子放进大盒子里。现在我们必须确定有多少个可见的盒子,例如。

'
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

找到解决方案的方法

在这个问题中,我们的方法是在前进的过程中对数组进行排序。我们现在将元素推入队列。随着我们的进展,我们将检查当前元素是否大于或等于队列前面的元素的两倍。如果是真的,我们现在弹出前面的元素。最后,我们将当前元素推入队列。我们的答案将是队列在最后的大小。

示例

'
#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;
}

输出

'
3

结论

在本教程中,我们解决了一个问题,即在将一个盒子放入另一个盒子后找到可见盒子的数量。我们还学习了该问题的 C++ 程序以及解决该问题的完整方法(普通)。我们可以用其他语言比如C、java、python等语言来编写同样的程序。我们希望本教程对您有所帮助。

卓越飞翔博客
上一篇: 在C程序中,编译时错误和运行时错误之间的区别是什么?
下一篇: 返回列表

相关推荐

留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏