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.
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 operations K. 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 4Sample Output
6 FILL(2) POUR(2,1) DROP(1) POUR(2,1) FILL(2) POUR(2,1)
bfs()搜索 dfs()打印路径。
题目大意:给你A B 容积的瓶子,有六个操作FILL(1),FILL(2),DROP(1),DROP(2),POUR(1,2),POUR(2,1),
加满A,加满B,倒光A,倒光B,把B倒到A,把A倒到B;
当输出AB两个瓶子的水到达C容量的最小步数和打印路径,如果到达不了输出:impossible;
解题思路:用bfs()搜索,每一步模拟六种方式,如果当AB有一个到达C就跳出,可以使用
struct node{
int formx, formy, step, op;}v[maxn][maxn];
来记录路径,结果dfs()输出就路径就好了。
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<queue>
using namespace std;
#define maxn 110
int A,B,C;
char a[10][10] = { "FILL(1)","FILL(2)","DROP(1)","DROP(2)","POUR(1,2)","POUR(2,1)"};
struct node{
int formx, formy, step, op;
}v[maxn][maxn];
struct point{
int x,y;
};
void dfs(int x,int y)
{
if(x == 0 && y == 0)
{
return ;
}
dfs(v[x][y].formx,v[x][y].formy);
printf("%s\n",a[v[x][y].op]);
}
void bfs()
{
queue <point> Q;
point s,q;
s.x = s.y = 0;
v[0][0].step = 1;
Q.push(s);
while(Q.size())
{
s = Q.front();
Q.pop();
if(s.x == C || s.y == C)
{
printf("%d\n",v[s.x][s.y].step - 1);
dfs(s.x,s.y);
return ;
}
for(int i=0; i<6; i++)
{
q = s;
if(i == 0)
{
q.x = A;
}
else if(i == 1)
{
q.y = B;
}
else if(i == 2)
{
q.x = 0;
}
else if(i == 3)
{
q.y = 0;
}
else if(i == 4)
{
if(q.x + q.y <= B)
{
q.y += q.x, q.x = 0;
}
else
{
q.x -= (B-q.y), q.y = B;
}
}
else if(i == 5)
{
if(q.x + q.y <= A)
{
q.x += q.y;
q.y = 0;
}
else
{
q.y -= (A-q.x);
q.x = A;
}
}
if(v[q.x][q.y].step == 0)
{
v[q.x][q.y].step = v[s.x][s.y].step +1;
v[q.x][q.y].formx = s.x;
v[q.x][q.y].formy = s.y;
v[q.x][q.y].op = i;
Q.push(q);
}
}
}
printf("impossible\n");
}
int main()
{
while(~scanf("%d%d%d",&A,&B,&C))
{
memset(v,0,sizeof(v));
bfs();
}
return 0;
}