在C++中判斷是否可以實現杯子和架子的整齊擺放
概念
針對給定的三種不同型別的杯子 (p[]) 和碟子 (q[]),以及 m 個架子,確定是否可以實現杯子和架子的整齊擺放。
杯子和碟子的擺放將被認為是整齊的,如果它遵循以下規則:
- 根據第一條規則,任何一個架子都不能同時包含杯子和碟子。
- 根據第二條規則,任何一個架子中最多隻能有 5 個杯子。
- 根據第三條規則,任何一個架子中最多隻能有 10 個碟子。
輸入
p[] = {4, 3, 7} q[] = {5, 9, 10} m = 11
輸出
Yes
解釋
杯子總數 = 14,所需架子數 = 3
碟子總數 = 24,所需架子數 = 3
因此,所需架子總數 = 3 + 3 = 6,
小於給定的架子數 m。所以,輸出為 Yes。
輸入
p[] = {5, 8, 5} q[] = {4, 10, 11} m = 3
輸出
No
杯子總數 = 18,所需架子數 = 4
碟子總數 = 25,所需架子數 = 3
因此,所需架子總數 = 4 + 3 = 7,
大於給定的架子數 m。所以,輸出為 No。
方法
為了擺放杯子和碟子,確定杯子的總數 p 和碟子的總數 q。因為同一個架子中不可能超過 5 個杯子,所以用公式 (p+5-1)/5 確定杯子所需的最大架子數,並用公式 (q+10-1)/10 確定碟子所需的最大架子數。如果這兩個值的和等於或小於 m,則擺放是可能的,否則不是。
示例
// C++ code to find if neat // arrangement of cups and // shelves can be made #include<bits/stdc++.h> using namespace std; // Shows function to check arrangement void canArrange1(int p[], int q[], int m){ int sump = 0, sumq = 0; // Used to calculate total number // of cups for(int i = 0; i < 3; i++) sump += p[i]; // Used to calculate total number // of saucers for(int i = 0; i < 3; i++) sumq += q[i]; // Now adding 5 and 10 so that if the // total sum is smaller than 5 and // 10 then we can get 1 as the // answer and not 0 int mp = (sump + 5 - 1) / 5; int mq = (sumq + 10 - 1) / 10; if(mp + mq <= m) cout << "Yes"; else cout << "No"; } // Driver code int main(){ // Shows number of cups of each type int p[] = {4, 3, 7}; // Shows number of saucers of each type int q[] = {5, 9, 10}; // Shows number of shelves int m = 10; // ndicates calling function canArrange1(p, q, m); return 0; }
輸出
Yes
廣告