使用了 DFS,并模拟倒牛奶的过程。
注意DFS处理回溯的方法:
int t1,t2,t3,i,j; for(i=0;i<3;i++){ for(j=0;j<3;j++){ t1 = b[0].m; t2 = b[1].m; t3 = b[2].m; if( dao(i,j)){ dfs(b[0].m, b[1].m, b[2].m); } //回溯到原来的状态 b[0].m = t1; b[1].m = t2; b[2].m = t3; } }
代码:
/*ID: nenusb1LANG: CTASK: milk3 */#include#include #include int map[21][21][21];//表示状态 typedef struct{ int c;//capacity int m;//milk}buk;buk b[3];int dao(int f, int t){//f桶倒入t桶 if(f==t || b[f].m == 0 || b[t].m == b[t].c){ return 0; } int temp = b[t].c - b[t].m; if(b[f].m > temp){//t桶能被倒满 b[f].m -= temp; b[t].m = b[t].c; }else{//f桶被倒空 b[t].m += b[f].m; b[f].m = 0; } return 1;}int dfs(int x, int y, int z){//参数是3个桶当前的牛奶 if(map[x][y][z]){ return 0; } map[x][y][z] = 1; int t1,t2,t3,i,j; for(i=0;i<3;i++){ for(j=0;j<3;j++){ t1 = b[0].m; t2 = b[1].m; t3 = b[2].m; if( dao(i,j)){ dfs(b[0].m, b[1].m, b[2].m); } //回溯到原来的状态 b[0].m = t1; b[1].m = t2; b[2].m = t3; } } return 0; } int main(){ freopen("milk3.in","r",stdin); freopen("milk3.out","w",stdout); int i,j; for(i=0; i<3; i++){ scanf("%d",&b[i].c); b[i].m = 0; } int total = b[2].c; b[2].m = total;//C桶是满的 int list[20]; memset(list,0,sizeof(list)); memset(map,0,sizeof(map)); dfs(0,0,total); for(i=0; i<=total; i++){ for(j=0; j<=total; j++){ if(map[0][i][j]){ list[j] = 1; } } } for(i=0; i