Video Solution
By David Zhou
Video Solution Code (DFS + BFS Explanation; Only BFS Code)
Solution 1 (DFS)
Explanation
We can perform a DFS starting from the base state of , where both pails have units of milk.
Note that we need to use a 3D grid to correctly track visited states, though. This is because the DFS may visit the same state earlier in its processing but through a greater number of operations. To properly track visited cells, we need to make sure the visited grid has a record for how many operations it took to reach each state every time.
Simulating all six operations every time is enough to pass the constraints.
Implementation
Time Complexity:
MAX_OPS = 100x, y, k, m = map(int, open("pails.in", "r").read().split())sol = float("inf")vis = [[[False for a in range(MAX_OPS + 1)] for b in range(MAX_OPS + 1)]for c in range(MAX_OPS + 1)]
Solution 2 (BFS)
Explanation
We can directly simulate all operations using BFS.
In this problem, we care about states where pail has and pail has units of milk. We can perform a BFS starting from base state to compute , the minimum number of steps to reach each state. Afterwards, compute the answer by iterating over all states where and finding the minimum .
For every transition in the BFS, we simulate all possible actions.
- Fill either pail completely to the top: set to or to .
- Empty either pail: set or to .
- Pour the contents of one pail into another without overflowing or running out of milk.
To perform operation 3, we can find the amount poured to be or depending on which pail you pour from. Then add/subtract this quantity to each pail appropriately.
Now iterate over all states where and compute the minimum .
Implementation
Time Complexity:
from collections import dequeimport syssys.stdin, sys.stdout = open("pails.in", "r"), open("pails.out", "w")input = sys.stdin.readlinedef generate_permutations(p1: int, p2: int):# generates results of all possible poursda = min(p2, x - p1) # amount poured when pouring p2 into p1
Solution 3 (DP)
Explanation
The states in this problem are a combination of the milk amounts in each pail and the number of operations to reach such amounts.
Let represent if it is possible to reach and pail amounts in operations. Our base case is as true, since there is no milk initially. Now, iterate through all such that , and all possible and . For any true state , mark as true for all 's that can result from a single operation based on . The possible operations are explained in the previous solutions.
The answer is the minimum of for all true .
Implementation
Time Complexity:
#include <climits>#include <fstream>#include <vector>using namespace std;int main() {ifstream fin("pails.in");int x, y, k, m;fin >> x >> y >> k >> m;
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!