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等)中編寫相同的程式。我們希望您覺得本教程有所幫助。

更新於: 2021年11月25日

275 次檢視

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告