用 C++ 实现不浪费食材的汉堡数量

c++server side programmingprogramming

假设我们有两个整数,tomatoSlices 和 cheeseSlices。它们分别代表不同汉堡的配料 −

  • 巨型汉堡:4 片番茄片和 1 片奶酪片。
  • 小汉堡:2 片番茄片和 1 片奶酪片。

我们需要求出 [total_jumbo, total_small],使得剩余的 tomatoSlices 数量为 0,cheeseSlices 数量也为 0。如果无法使剩余的 tomatoSlices 和 cheeseSlices 数量为 0,则返回 []。因此,如果输入为 tomatoSlices = 16 和 chesseSlices = 7,则输出为 [1, 6]。因此,这意味着,要制作一个巨型汉堡和六个小汉堡,我们需要 4*1 + 2*6 = 16 片番茄片和 1 + 6 = 7 片奶酪片。

为了解决这个问题,我们将遵循以下步骤 −

  • 创建一个名为 ans 的数组
  • 如果番茄为奇数或奶酪 > 番茄/2 或番茄 > 4*奶酪,则返回 ans
  • x := (4 * 奶酪 - 番茄) / 2
  • y := (番茄 - (2*x)) / 4
  • 将 y 和 x 插入数组 ans
  • 返回 ans

让我们看看下面的实现以便更好地理解 −

示例

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   vector<int> numOfBurgers(int t, int c) {
      vector <int> ans;
      if(t % 2 != 0 || c > t/2 || t > c*4)return ans;
      int x = (4 * c - t) / 2;
      int y = ( t - (2 * x) )/ 4;
      ans.push_back(y);
      ans.push_back(x);
      return ans;
   }
};
main(){
   Solution ob;
   print_vector(ob.numOfBurgers(16,7));
}

输入

16
7

输出

[1, 6, ]

相关文章