Problem Description
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 poti 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 exactlyC liters of water in one of the pots.
Input
<p>On the first and only line are the numbers <b>A</b>, <b>B</b>, and <b>C</b>. These are all integers in the range from 1 to 100 and <b>C</b>≤max(<b>A</b>,<b>B</b>).</p>
Output
<p>The first line of the output must contain the length of the sequence of operations <b>K</b>. The following <b>K</b> 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 ‘<b>impossible</b>’.</p>
Sample Input
3 5 4
Sample Output
6 FILL(2) POUR(2,1) DROP(1) POUR(2,1) FILL(2) POUR(2,1)
杯子为a b大小,几步能有一个杯子变为c。
思路:
有六中倒水方法,不断搜索,直到找出方案,或者不可以。回溯输出是用一个数组存数据,用结构体中的一个变量做父节点。
代码:
#include <iostream>
#include <string>
#include <queue>
#include <cstring>
using namespace std;
int l1,r1,sum,f=0;
int map[101][101];
int st[10100];
int y;
string ww[7]={"","FILL(1)","FILL(2)","DROP(1)","DROP(2)","POUR(1,2)","POUR(2,1)"};
struct poin
{
int l,r;
int t;
int bu;
int u;
}po[10005];
int j;
int printf()
{ int an=0;
while(y!=0)
{
st[an++]=po[y].bu;
y=po[y].u;
}
cout<<an<<endl;
for(int i=an-1;i>=0;i--)
{
cout<<ww[st[i]]<<endl;
}
}
int genxin(int n,int m,int k)
{
if(map[n][m])return 0;
map[n][m]=1;
po[j].l=n;
po[j].r=m;
po[j].u=y;
po[j].bu=k;
j++;
}
int bfs()
{ po[0].l=0;
po[0].r=0;
int dx,dy;
y=0;
j=1;
while(y!=j)
{
if(po[y].l==sum||po[y].r==sum){printf();return 0;}
//1
dx=l1;
dy=po[y].r;
genxin(dx,dy,1);
//2
dx=po[y].l;
dy=r1;
genxin(dx,dy,2);
//3
dx=0;
dy=po[y].r;
genxin(dx,dy,3);
//4
dx=po[y].l;
dy=0;
genxin(dx,dy,4);
//5
dx=po[y].l+min(l1-po[y].l,po[y].r);
dy=po[y].r-min(l1-po[y].l,po[y].r);
genxin(dx,dy,6);
//6
dx=po[y].l-min(r1-po[y].r,po[y].l);
dy=po[y].r+min(r1-po[y].r,po[y].l);
genxin(dx,dy,5);
y++;
}
if(y>=j){cout<<"impossible"<<endl;}
}
int main()
{
while(cin>>l1>>r1>>sum)
{
memset(map,0,sizeof(map));
map[0][0]=1;
bfs();
}
return 0;
}