//有两个空杯子一二,容量分别为aL,bL,现在给你一个数c; //问是否可以用一二两个杯子 倒出cL的水,输出最少步骤的倒水的过程 //如果不能就输出impossible //有六种情况, a倒进b中,或b倒进a中 // a清空或b清空 // a倒满或b倒满 #include<stdio.h> #include<string.h> #include<algorithm> using namespace std;
int a,b,c,k,flag;
int book[110][110];
int step1[1000];
int step2[1000];
void dfs(int x,int y,int step) { int tx,ty; if(step >= k)return; if(x == c || y == c) { k = step; flag = 1; for(int i = 0; i < k; i++) step2[i] = step1[i]; //记录步骤 return ; } for(int i = 0; i < 6; i++) { if(i == 0) { tx = a; ty = y; } //水杯一倒满 else if(i == 1) { tx = x; ty = b; } //水杯二倒满 else if(i == 2) { tx = 0; ty = y; } //水杯一清空 else if(i == 3) { tx = x; ty = 0; } //水杯二清空 else if(i == 4) { if(x + y <= b) { ty = x + y; tx = 0; } //把水杯一中的水倒进水杯二中且不会溢出 else { ty = b; tx = x + y - b; }//如果溢出 } else if(i == 5) { if( x + y <= a) { tx = x + y; ty = 0; } //把水杯二中的水倒进水杯一中且不会溢出 else { tx = a; ty = x + y - a; }//如果溢出 } if(!book[tx][ty]) { book[tx][ty] = 1; step1[step] = i; //存储步骤 dfs(tx,ty,step+1); book[tx][ty] = 0; } } return ; } int main() { while(~scanf("%d%d%d",&a,&b,&c)) { memset(book,0,sizeof(book)); k = 999999; flag = 0; book[0][0] = 1; dfs(0,0,0); if(flag) { printf("%d\n",k); for(int i = 0; i < k; i++) { if(step2[i] == 0)printf("FILL(1)\n"); else if(step2[i] == 1)printf("FILL(2)\n"); else if(step2[i] == 2)printf("DROP(1)\n"); else if(step2[i] == 3)printf("DROP(2)\n"); else if(step2[i] == 4)printf("POUR(1,2)\n"); else if(step2[i] == 5)printf("POUR(2,1)\n"); } } else printf("impossible\n"); } return 0; }
POJ3414
最新推荐文章于 2019-04-22 20:49:30 发布