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 potj 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.
On the first and only line are the numbers A, B, and C. These are all integers in the range from 1 to 100 and C≤max(A,B).
The first line of the output must contain the length of the sequence of operationsK. The following K lines must each describe one operation. If there are several sequences of minimal length, output any one of them. If the desired result can’t be achieved, the first and only line of the file must contain the word ‘impossible’.
3 5 4
6 FILL(2) POUR(2,1) DROP(1) POUR(2,1) FILL(2) POUR(2,1)
bfs
代码如下:
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
const int Nmax=103;
bool book[Nmax][Nmax];
int a,b,c;
int r,l;
int step[Nmax];
struct Pot{
int ca,cb;
int count;//记录当前的操作
int pre;//记录上一步的路径
}p[Nmax*Nmax];
string name[]={" ", "FILL(1)", "FILL(2)", "DROP(1)", "DROP(2)", "POUR(2,1)", "POUR(1,2)"};
void display()
{
int ant=0;
while(l!=0)
{
step[ant++]=p[l].count;
l=p[l].pre;
}
cout<<ant<<endl;
for(int i=ant-1;i>=0;i--)
cout<<name[step[i]]<<endl;
}
void bfs()
{
r=l=0;
p[0].ca=0;
p[0].cb=0;
p[0].count=0;
p[0].pre=0;
book[0][0]=true;
r++;
while(l<r)
{
if(p[l].ca==c||p[l].cb==c)
{
display();
return;
}
p[r].ca=a;//1满
p[r].cb=p[l].cb;
if(!book[p[r].ca][p[r].cb])
{
book[p[r].ca][p[r].cb]=true;
p[r].count=1;
p[r].pre=l;
r++;
}
p[r].ca=p[l].ca;//2满
p[r].cb=b;
if(!book[p[r].ca][p[r].cb])
{
book[p[r].ca][p[r].cb]=true;
p[r].count=2;
p[r].pre=l;
r++;
}
p[r].ca=0;//1空
p[r].cb=p[l].cb;
if(!book[p[r].ca][p[r].cb])
{
book[p[r].ca][p[r].cb]=true;
p[r].count=3;
p[r].pre=l;
r++;
}
p[r].ca=p[l].ca;//2空
p[r].cb=0;
if(!book[p[r].ca][p[r].cb])
{
book[p[r].ca][p[r].cb]=true;
p[r].count=4;
p[r].pre=l;
r++;
}
p[r].cb=min(b,p[l].ca+p[l].cb);
p[r].ca=p[l].ca-(p[r].cb-p[l].cb);//1到2
if(!book[p[r].ca][p[r].cb])
{
book[p[r].ca][p[r].cb]=true;
p[r].count=6;
p[r].pre=l;
r++;
}
p[r].ca=min(a,p[l].ca+p[l].cb);//2到1
p[r].cb=p[l].cb-(p[r].ca-p[l].ca);
if(!book[p[r].ca][p[r].cb])
{
book[p[r].ca][p[r].cb]=true;
p[r].count=5;
p[r].pre=l;
r++;
}
l++;
}
cout<<"impossible"<<endl;
}
int main()
{
while(cin>>a>>b>>c)
{
memset(book,0,sizeof(book));
bfs();
}
return 0;
}