[面试] 水杯题实现

水杯题的代码实现:两个水杯a, b. 倒出c升水

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int gcd(int a, int b)
 5 {
 6     if (b == 0)
 7         return a;
 8     else
 9         return gcd(b, a % b);
10 }
11 
12 void solve(int a, int b, int curA, int curB, int c)
13 {
14     if (curA == c)
15         return;
16     if (curB == c)
17         return;
18     if (curA + curB == c)
19         return;
20 
21     if (curA == 0)
22     {
23         cout << "full(A) " << "a:" << curA << " b:" << curB << endl;
24         return solve(a, b, a, curB, c);
25     }
26     else if (curB == b)
27     {
28         cout << "empty(B) " << "a:" << curA << " b:" << curB << endl;
29         return solve(a, b, curA, 0, c);
30     }
31     else
32     {
33         int emptyB = b - curB;
34         if (curA >= emptyB)
35         {
36             curB = b;
37             curA -= emptyB;
38         }
39         else
40         {
41             curB += curA;
42             curA = 0;
43         }
44 
45         cout << "A->B " << "a:" << curA << " b:" << curB << endl;
46         return solve(a, b, curA, curB, c);
47     }
48 }
49 
50 int main()
51 {
52     int a, b, c;
53 
54     while(cin >> a >> b >> c)
55     {
56         if (a + b == c)
57             cout << "full(a), full(b) " << "a:" << a << " b:" << b << endl;
58         else if (a + b < c)
59             cout << "No ans!" << endl;
60         else
61         {
62             int d = gcd(a, b);
63             if (c % d == 0)
64             {
65                 if (a < b)
66                 {
67                     int t = a;
68                     a = b;
69                     b = t;
70                 }
71                 solve(a, b, 0, 0, c);
72             }
73             else
74                 cout << "No ans!" << endl;
75         }
76     }
77 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值