首頁 > 後端開發 > C++ > 主體

C++程式:找出將一個盒子放入另一個盒子後可見的盒子數量

王林
發布: 2023-09-11 23:37:02
轉載
1267 人瀏覽過

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++程式:找出將一個盒子放入另一個盒子後可見的盒子數量的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!