Milk Pails WA 1 testcase

Problem link.
I use floodfill to store the “states”, which represent the sizes of the two buckets. The c variable in my dfs function refers tot he number of moves FJ made so far, which must always be \le K.

#include <bits/stdc++.h>
using namespace std;

int x, y, k, m;
bool vis[101][101] = {{0}};

int ans;
void dfs(int a, int b, int c){ // c = # of moves made so far
    if(c>k || vis[a][b]) return;
    vis[a][b] = true;
    ans = min(ans, abs(m-a-b));
    dfs(x, b, c+1), dfs(a, y, c+1); // fill pail completely
    dfs(0, b, c+1), dfs(a, 0, c+1); // empty pail
    int p1 = min(a, y-b), p2 = min(b, x-a);
    dfs(a-p1, b+p1, c+1); // pour from a to b
    dfs(a+p2, b-p2, c+1); // pour from b to a
}

int main()
{
    freopen("pails.in", "r", stdin);
    freopen("pails.out", "w", stdout);
    cin >> x >> y >> k >> m;
    ans = m;
    dfs(0, 0, 0);
    cout << ans << endl;
}

I receive a WA on test case 8, while all other test cases pass within a few milliseconds. I tried changing a few things, such as

  • setting ans = 1e9,
  • vis[0][0] = 1 prior to dfs and if(c>k || (c && vis[a][b])) return; within dfs,
  • extending the size of the vis matrix (number of states),

but these are insignificant changes. Can you please help me fix my mistake?

I could be completely wrong since I didn’t read the problem yet :cowboy_hat_face: but shouldn’t your visited array have three dimensions, a b and c? Because arriving at state (a, b) with 10 moves spent isn’t the same as arriving at state (a, b) with only 5 moves spent right?