题目大意:有容积为A,B大小的罐子,需要得到C的水,可以通过6种操作获得,最少需要几步,怎么做。如果不能则输出impossible。
解题思路:感觉有点像非常可乐和迷宫问题结合。就是既要考虑倒水,也要保存路径,综合一下就可以了,只是比较麻烦一些。
ac代码:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
struct pour{int x;int y;string a;int pre;
}po[505];
int a, b, c, vis[205][205], temp;
int front, rear;
int bfs()
{front = rear = 0;po[0].x = po[0].y = 0;po[0].pre = -1;vis[0][0] = 0;rear++;while (front < rear){pour temp = po[front];front++;int tt = temp.x, kk = temp.y;if (tt == c || kk == c)return vis[tt][kk];if (tt < a && vis[a][kk] == -1){temp.x = a, temp.y = kk;temp.pre = front - 1;temp.a = "FILL(1)";po[rear] = temp;rear++;vis[a][kk] = vis[tt][kk] + 1;} if (kk < b && vis[tt][b] == -1){temp.x = tt, temp.y = b;temp.pre = front - 1;temp.a = "FILL(2)";po[rear] = temp;rear++;vis[tt][b] = vis[tt][kk] + 1;}if (tt > 0){if (vis[0][kk] == -1){temp.x = 0, temp.y = kk;temp.pre = front - 1;temp.a = "DROP(1)";po[rear] = temp;rear++;vis[0][kk] = vis[tt][kk] + 1; }if (kk < b){if (tt > (b-kk)){temp.x = tt - (b - kk), temp.y = b;temp.pre = front - 1;temp.a = "POUR(1,2)";if (vis[temp.x][b] == -1){po[rear] = temp;rear++;vis[temp.x][b] = vis[tt][kk] + 1;} }else{temp.x = 0, temp.y = tt + kk;temp.pre = front - 1;temp.a = "POUR(1,2)";if (vis[0][tt+kk] == -1){po[rear] = temp;rear++;vis[0][tt+kk] = vis[tt][kk] + 1; }}} }if (kk > 0){if (vis[tt][0] == -1){temp.x = tt, temp.y = 0;temp.pre = front - 1;temp.a = "DROP(2)";po[rear] = temp;rear++;vis[tt][0] = vis[tt][kk] + 1; }if (tt < a){if (kk > (a-tt)){temp.x = a, temp.y = kk - (a - tt);temp.pre = front - 1;temp.a = "POUR(2,1)";if (vis[a][temp.y] == -1){po[rear] = temp;rear++;vis[a][temp.y] = vis[tt][kk] + 1;} }else{temp.x = tt + kk, temp.y = 0;temp.pre = front - 1;temp.a = "POUR(2,1)";if (vis[tt+kk][0] == -1){po[rear] = temp;rear++;vis[tt+kk][0] = vis[tt][kk] + 1; }}} }}
return 0;
}
void prin(pour p)
{if (p.pre == -1)return ;else{prin(po[p.pre]);cout << p.a << endl;}
}
int main()
{while (scanf("%d%d%d", &a, &b, &c)!=EOF){memset(vis, -1, sizeof(vis));temp = bfs();if (temp){printf("%d\n", temp);prin(po[front-1]);}elseprintf("impossible\n");}
return 0;
}