使用C++,用兩個容器和無限量的水測量一升水


在這個問題中,我們有兩個容量分別為x和y的容器,以及無限量的水。我們的任務是建立一個程式,能夠精確地在一個容器中計算出一升水。條件是x和y互質。**互質**也稱為*互素*,是指兩個數只有1作為它們唯一的公約數。這意味著它們的gcd(*最大公約數*)為1。

這裡,假設我們有兩個容器V1,容量為x,V2,容量為y。為了使用這兩個容器測量一升水,我們將首先從水源中裝滿一個容器,然後將其倒入第二個容器。重複此過程,直到容器V1中包含一升水。

讓我們舉個例子來理解這個問題:

輸入

V1 = 5, V2 = 8
V1 = 5 ; V2 = 0 -> pour water from V1 to V2 and refill it.
V1 = 5 ; V2 = 5 -> pour water from V1 to V2 and refill it.
V1 = 2 ; V2 = 0 -> pour water from V1 to V2. Now, V2 is filled, empty it.
V1 = 5 ; V2 = 2 -> pour water from V1 to V2 and refill it.
V1 = 5 ; V2 = 7 -> pour water from V1 to V2 and refill it.
V1 = 4 ; V2 = 0 -> pour water from V1 to V2. Now, V2 is filled, empty it.
V1 = 1 ; V2 = 0 -> pour water from V1 to V2 and refill it.
Here, V1 measures 1 litre of water.

示例

演示解決方案的程式:

線上演示

#include <iostream>
using namespace std;
int x, y, V1, V2 = 0;
int transferWater(int amt1, int amt2) {
   if (amt1 + amt2 < y){
      V2 += V1;
      return V1;
   }
   int transferred = y - V2;
   V2 = 0;
   return transferred;
}
void measure1Litre() {
   while(V1 != 1){
      if (V1 == 0)
         V1 = x;
      cout<<"Vessel 1: "<<V1<<" | Vessel 2: "<<V2<<endl;
      V1 = V1 - transferWater(V1, V2);
   }
   cout<<"Vessel 1: "<<V1<<" | Vessel 2: "<<V2<<endl;
}
int main() {
   x= 5, y = 8;
   measure1Litre();
   return 0;
}

輸出

Vessel 1: 5 | Vessel 2: 0
Vessel 1: 5 | Vessel 2: 5
Vessel 1: 2 | Vessel 2: 0
Vessel 1: 5 | Vessel 2: 2
Vessel 1: 5 | Vessel 2: 7
Vessel 1: 4 | Vessel 2: 0
Vessel 1: 5 | Vessel 2: 4
Vessel 1: 1 | Vessel 2: 0

更新於:2020年6月3日

瀏覽量:117

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告