恩,首先解释题意啦,啦啦啦,给你两个容器容量分别是A,B,可以对A,B两个锅进行三个操作,
1:FILL(i)把i锅装满
2:DROP(i)把i锅的水倒空
3:POUR(i,j)把i锅的水倒入j锅,直到j锅装满
然后如果能把A或者B装成C的容量则打印最短步骤,否则打印‘impossible’;
思路:一看就是bfs题了,求最短啥的一般都用bfs,做这种题一定
要注意的是状态标记与状态转移,
#include<iostream>
#include<cstring>
using namespace std;
const int Max = 101;
struct node{
int ope; int a; int b; node *pre;
}que[Max * Max]; // 队列结点,ope记录第几种操作,a,b记录此结点两个pot的水数。
bool vis[Max][Max];
char str[6][10] = {"FILL(1)", "FILL(2)", "DROP(1)", "DROP(2)", "POUR(1,2)", "POUR(2,1)"};
// 各操作对应输出的字符串。
int min(int a, int b){
return a < b ? a : b;
}
void print(node now){
if(now.pre != NULL){
print(*now.pre);
cout << str[now.ope] << endl;
}
}
//递归调用输出步骤
void bfs(int a, int b, int c){
int steps = 0;
int head = 0, tail = 1;
que[0].a = que[0].b = 0;
que[0].pre = NULL;
while(tail - head > 0){
int count = tail - head;
while(count --){
node now = que[head];
if(now.a == c || now.b == c){
cout << steps << endl;
print(now);
return;
}
if(!vis[a][now.b]){
que[tail].ope = 0;
que[tail].a = a;
que[tail].b = now.b;
que[tail].pre = &que[head];
vis[a][now.b] = true;
tail ++;
}
if(!vis[now.a][b]){
que[tail].ope = 1;
que[tail].a = now.a;
que[tail].b = b;
que[tail].pre = &que[head];
vis[now.a][b] = true;
tail ++;
}
if(!vis[0][now.b]){
que[tail].ope = 2;
que[tail].a = 0;
que[tail].b = now.b;
que[tail].pre = &que[head];
vis[0][now.b] = true;
tail ++;
}
if(!vis[now.a][0]){
que[tail].ope = 3;
que[tail].a = now.a;
que[tail].b = 0;
que[tail].pre = &que[head];
vis[now.a][0] = true;
tail ++;
}
int wat1 = min(now.a, b - now.b);
if(!vis[now.a - wat1][now.b + wat1]){
que[tail].ope = 4;
que[tail].a = now.a - wat1;
que[tail].b = now.b + wat1;
que[tail].pre = &que[head];
vis[now.a - wat1][now.b + wat1] = true;
tail ++;
}
int wat2 = min(a - now.a, now.b);
if(!vis[now.a + wat2][now.b - wat2]){
que[tail].ope = 5;
que[tail].a = now.a + wat2;
que[tail].b = now.b - wat2;
que[tail].pre = &que[head];
vis[now.a + wat2][now.b - wat2] = true;
tail ++;
}
head ++;
}
steps ++;
}
cout << "impossible" << endl;
}
int main(){
int a, b, c;
cin >> a >> b >> c;
memset(vis, false, sizeof(vis));
vis[0][0] = true;
bfs(a, b, c);
return 0;
}