[面试] 水杯题实现

水杯题的代码实现:两个水杯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 }
posted @ 2012-11-21 23:36  chkkch  阅读(422)  评论(0编辑  收藏  举报