You are given two pots, having the volume of A and B liters respectively. The following operations can be performed:
FILL(i) fill the pot i (1 ≤ i ≤ 2) from the tap;
DROP(i) empty the pot i to the drain;
POUR(i,j) pour from pot i to pot j; after this operation either the pot j is full (and there may be some water left in the pot i), or the pot i is empty (and all its contents have been moved to the pot j).
Write a program to find the shortest possible sequence of these operations that will yield exactly C liters of water in one of the pots.
题解 :搜索并不是这个题的难点,难在如何记录路径,我用的是一个数组去存没一步,然后用结构体指针回溯
#include <iostream>
#include <cstring>
#include <queue>
#include <stack>
using namespace std;
int a,b,c,vis[105][105];
char asd[10][20]={"FILL(1)","FILL(2)","DROP(1)","DROP(2)","POUR(1,2)","POUR(2,1)"};
struct node
{
int a,b,cnt;
int flag; //记录操作类型
node *pre; //记录路径
};
node l[105*105];
stack <int> ans;
void Print()
{
while(!ans.empty()){
printf("%s\n",asd[ans.top()]);
ans.pop();
}
}
void bfs()
{
queue <node> q;
node w;
w.a = 0; w.b=0;w.cnt=0;w.pre=NULL,w.flag = -1;
q.push(w);
vis[0][0]=1;
int res = -1;
while(q.size()){
res++ ;
node f=q.front();
l[res] = f;
q.pop();
for(int i=0;i<6;i++){
w=f;
if(i==0){
w.a = a;
}
else if(i==1){
w.b=b;
}
else if(i==2){
w.a=0;
}
else if(i==3){
w.b=0;
}
else if(i==4){
if(f.a > b-f.b){
w.a -= b-w.b;
w.b =b;
}
else{
w.b += w.a;
w.a = 0;
}
}
else if(i==5){
if(f.b > a-f.a){
w.b -= a-w.a;
w.a = a;
}
else{
w.a += w.b;
w.b = 0;
}
}
w.flag = i;
if(!vis[w.a][w.b]){
w.cnt = f.cnt+1;
vis[w.a][w.b]=1;
w.pre = &l[res];
if(w.a==c || w.b==c){
cout << w.cnt <<endl;
while(w.pre != NULL){
ans.push(w.flag);
w = *w.pre;
}
Print();
return ;
}
q.push(w);
}
}
}
cout << "impossible" <<endl;
return ;
}
int main()
{
cin >> a >> b >> c;
bfs();
return 0;
}