用N盧比在C++中能買到的最大升數的水


我們有N盧比。目標是用這筆錢買儘可能多的水,水瓶的價格如下:

  • 塑膠瓶:A盧比/1升
  • 玻璃瓶:B盧比/1升
  • 玻璃瓶:B盧比/1升

歸還後,玻璃瓶的原始成本變為B-E盧比。

如果塑膠瓶的成本仍然低於B-E,則只購買塑膠瓶。否則,購買N-E/(B-E)個玻璃瓶,並將剩餘的錢用於購買塑膠瓶。

輸入

N = 6, A = 5, B = 4, E = 3;

輸出

Maximum litres of water: 3

解釋 − B-E=1, 1<A N-E=3, 用3盧比買了3個1升的玻璃瓶

輸入

N = 10, A = 5, B = 10, E = 3;

輸出

Maximum litres of water: 2

解釋 − B-E=7, 7>A n/a= 10/5 = 2 個塑膠瓶可以購買

下面程式中使用的演算法如下:

  • 整數money、bottle、gbottle和gempty用於表示價格和我們擁有的金額。

  • 函式maxWater(int mny,int pb,int gb,int ge)將所有值作為引數,並列印可以購買的水量。

  • 變數litrs用於儲存計算出的水量(升)。

  • 我們將玻璃瓶的新值(原始值-返回值)作為pb傳遞。

  • 如果傳遞的gb值小於pb值,則購買(mny-ge)/gb個玻璃瓶。

  • 減去這個數量來計算剩餘的錢,mny-=ltrs*gb

  • 現在可以購買的塑膠瓶數量為mny/pb。

  • 如果傳遞的gb值大於pb值,則只購買mny/pb個塑膠瓶。

  • 兩種情況下都列印結果,因為瓶子的數量就是水的升數。每個瓶子的容量為1升。

示例

 線上演示

// CPP implementation of the above approach
#include<bits/stdc++.h>
using namespace std;
void maxWater(int mny,int pb,int gb,int ge){
   int litrs;
   // if buying glass bottles is profitable
   if (gb < pb){
      // no. of glass bottles
      int tmp=mny-ge/gb;
      litrs=tmp>0?tmp:0;
      mny-=litrs*gb;
      // no. of plastic bottles
      litrs+=mny/pb;
      cout<<"Maximum Liters of water : "<<litrs<<endl;
   }
   // only plastic bottles
   else
      cout<<"Maximum Liters of water only Plastic bottles: "<<(mny /pb)<<endl;
}
int main(){
   int money = 20, pbottle=5, gbottle=10, gempty = 8;
   gbottle=gbottle-gempty; //new cost of glass botlles
   maxWater( money,pbottle,gbottle,gempty );
}

輸出

Maximum Liters of water: 14

更新於:2020年8月3日

485 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.