使用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
广告