2019 Dec Gold Problem 1 Milk Pumping
Official Problem StatementEdit
Problem Statement:
Milk Pumping
Farmer John has N (1 <= N <= 1,000) cows, conveniently numbered 1..N. He needs to pump milk from each of them.
The cows are arranged in a line, and it takes one minute to pump milk from a cow. However, if two cows are adjacent, it takes only 30 seconds to pump milk from both of them simultaneously.
Help Farmer John determine the minimum amount of time it will take to pump milk from all of his cows.
Solution:
The solution to this problem is to use a greedy algorithm. We start at the first cow and check if the next cow is adjacent. If so, we pump milk from both cows simultaneously, which takes 30 seconds. If not, we pump milk from the current cow, which takes one minute. We continue this process until all cows have been milked.
The following C++ code implements this algorithm:
int N; // number of cows int time = 0; // total time to pump milk for (int i = 0; i < N; i++) {
if (i < N-1 && cows[i+1] - cows[i] == 1) { // adjacent cows, pump milk from both in 30 seconds time += 30; } else { // non-adjacent cows, pump milk from current cow in one minute time += 60; }
}
// Output the total time cout << time << endl;