Advertisement
pexea12

Minh Tong Quat

Sep 11th, 2015
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int max1, max2, max3, target;
  6.  
  7. int gcd(int x, int y) {
  8.       if (x % y == 0) return y;
  9.       return gcd(y, x % y);
  10. }
  11.  
  12. void pour(int &x, int &y, int maxY) {
  13.       // Pour from x to y
  14.       int remain = maxY - y;
  15.       if (remain > 0) {
  16.             if (x < remain) {
  17.                   y += x; x = 0;
  18.             } else {
  19.                   x -= remain; y = maxY;
  20.             }
  21.       }
  22. }
  23.  
  24.  
  25. void solve(int cup1, int cup2, int cup3, int target) {
  26.       int divisor = gcd(max1, gcd(max2, max3));
  27.       if (target % divisor != 0) {
  28.             cout << endl << "Unable to pour";
  29.             return;
  30.       }
  31.  
  32.       if (cup1 == target || cup2 == target || cup3 == target) {
  33.             cout << endl << "Done";
  34.             return;
  35.       }
  36.  
  37.       if (cup1 == 0) {
  38.             pour(cup3, cup1, max1);
  39.             cout << endl << "C -> A";
  40.       } else if (cup2 == 0) {
  41.             pour(cup1, cup2, max2);
  42.             cout << endl << "A -> B";
  43.       } else if (cup3 == 0) {
  44.             pour(cup2, cup3, max3);
  45.             cout << endl << "B -> C";
  46.       } else if (cup2 == max2) {
  47.             pour(cup2, cup3, max3);
  48.             cout << endl << "B -> C";
  49.       } else if (cup3 == max3) {
  50.             pour(cup3, cup1, max1);
  51.             cout << endl << "C -> A";
  52.       } else {
  53.             pour(cup2, cup3, max3);
  54.             cout << endl << "B -> C";
  55.       }
  56.  
  57.       solve(cup1, cup2, cup3, target);
  58. }
  59.  
  60. int main()
  61. {
  62.  
  63.       cout << endl << "Pouring Water";
  64.       cout << endl;
  65.       cout << endl << "Cup 1 has the most water.";
  66.       cout << endl << "Cup 1 (A) = "; cin >> max1;
  67.       cout << endl << "Cup 2 (B) = "; cin >> max2;
  68.       cout << endl << "Cup 3 (C) = "; cin >> max3;
  69.       cout << endl << "Target = "; cin >> target;
  70.       cout << endl << "Cup 1 is full and Cup 2, 3 is empty";
  71.  
  72.       solve(max1, 0, 0, target);
  73.  
  74.       return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement