C++: pouring milk problem


topic

Agriculture, especially the production of milk, is a highly competitive industry. Farmer John found out that if he didn't innovate in the milk production process, his dairy business could take a big hit!
Fortunately, Farmer John had a great idea. His three award-winning cows, Bessie, Elsie and Mildred, each produce milk with slightly different tastes, and he intends to mix the three milks to create the perfect taste.
In order to mix these three different kinds of milk, he brought three buckets containing the milk from three cows respectively. These barrels may have different volumes and may not be completely full. Then he pours milk from bucket 1 into bucket 2, then pours milk from bucket 2 into bucket 3, then pours milk from bucket 3 into bucket 1, then pours milk from bucket 1 into bucket 2, and so on cycle Operations are performed 100 times in total (so the 100th operation will be bucket 1 poured into bucket 2). When Farmer John pours milk from bucket a into bucket b, he pours as much milk as he can until bucket a is emptied or bucket b is full.
Please tell Farmer John how much milk will be in each bucket when he pours 100 times.

1. Input

10 3
11 4
12 5

2. Output

0
10
2

3. Idea + code

Initial state: 3 4 5

  1. Bucket 1 -> 2: 0 7 5
  2. Bucket 2 -> 3: 0 0 12
  3. Bucket 3 -> 1: 10 0 2
  4. Bucket 1 -> 2: 0 10 2
  5. Bucket 2->3: 0 0 12
    (then the last three states cycle through...)
#include<iostream>

using namespace std;

int c[10], m[10];

void turn_next(int a, int b){
    
    
    
    int x = c[b] - m[b];
    if(x >= m[a]) m[b] += m[a], m[a] = 0;
    else m[b] = c[b], m[a] -= x;
}

int main(){
    
    
    
    for(int i = 1; i <= 3; i++) cin >> c[i] >> m[i];
    
    for(int i = 0; i < 100; i++){
    
    
        
        int x = i % 3;
        if(x == 0) turn_next(1, 2);
        else if(x == 1) turn_next(2, 3);
        else turn_next(3, 1);
    }
    
    for(int i = 1; i <= 3; i++) cout << m[i] << endl;
    
    return 0;
}

Guess you like

Origin blog.csdn.net/qjyws/article/details/129093528