Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- int max1, max2, max3, target;
- int gcd(int x, int y) {
- if (x % y == 0) return y;
- return gcd(y, x % y);
- }
- void pour(int &x, int &y, int maxY) {
- // Pour from x to y
- int remain = maxY - y;
- if (remain > 0) {
- if (x < remain) {
- y += x; x = 0;
- } else {
- x -= remain; y = maxY;
- }
- }
- }
- void solve(int cup1, int cup2, int cup3, int target) {
- int divisor = gcd(max1, gcd(max2, max3));
- if (target % divisor != 0) {
- cout << endl << "Unable to pour";
- return;
- }
- if (cup1 == target || cup2 == target || cup3 == target) {
- cout << endl << "Done";
- return;
- }
- if (cup1 == 0) {
- pour(cup3, cup1, max1);
- cout << endl << "C -> A";
- } else if (cup2 == 0) {
- pour(cup1, cup2, max2);
- cout << endl << "A -> B";
- } else if (cup3 == 0) {
- pour(cup2, cup3, max3);
- cout << endl << "B -> C";
- } else if (cup2 == max2) {
- pour(cup2, cup3, max3);
- cout << endl << "B -> C";
- } else if (cup3 == max3) {
- pour(cup3, cup1, max1);
- cout << endl << "C -> A";
- } else {
- pour(cup2, cup3, max3);
- cout << endl << "B -> C";
- }
- solve(cup1, cup2, cup3, target);
- }
- int main()
- {
- cout << endl << "Pouring Water";
- cout << endl;
- cout << endl << "Cup 1 has the most water.";
- cout << endl << "Cup 1 (A) = "; cin >> max1;
- cout << endl << "Cup 2 (B) = "; cin >> max2;
- cout << endl << "Cup 3 (C) = "; cin >> max3;
- cout << endl << "Target = "; cin >> target;
- cout << endl << "Cup 1 is full and Cup 2, 3 is empty";
- solve(max1, 0, 0, target);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement