【USACO】Mother's Milk

/*
ID:
PROG: milk3
LANG: C++11
 */

#include 
#include 
#include 
#include 
#include 

using namespace std;
#define N 30
int A, B, C;
int amount;
int imax = -1;
bool state[N][N];
bool ans[N];
void dfs(int a, int b){
    if(state[a][b])
        return;
    state[a][b] = true;
    int c = amount - a - b;
    if (a == 0) {
        ans[c] = true;
        if(imax < c)
            imax = c;
    }
    if (a < A && a < amount){
        if (b > 0){
            dfs(a + min(A-a, b), b - min(A-a, b));
        }
        if (c > 0){
            dfs(a + min(A-a, c), b);
        }
    }
    if (b < B && b < amount){
        if (a > 0){
            dfs(a - min(a, B-b), b + min(a, B-b));
        }
        if (c > 0){
            dfs(a, b + min(B-b, c));
        }
    }
    if (c < C){
        if (a > 0){
            dfs(0, b);
        }
        if (b > 0){
            dfs(a, 0);
        }
    }

}

int main() {
    freopen("milk3.in", "r", stdin);
    freopen("milk3.out", "w", stdout);
    cin >> A >> B >> C;
    amount = C;
    memset(ans, 0, sizeof(ans));
    dfs(0, 0);
    for (int i = 0; i <= 20; i ++){
        if (ans[i]) {
            cout << i;
            if (i < imax)
                cout << ' ';
        }
    }
    cout << endl;
    return 0;
}

你可能感兴趣的:(USACO,回溯,搜索)