Pots
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 jis 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.
Input
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).
Output
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’.
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,现在有3种操作,1 把一个水壶灌满 2 把一个水壶倒空 3 把一个水壶的水倒到另一个水壶,把另一个水壶倒满为止,如果倒不满就全倒过去
思路:和走地图的思想差不多,只不过把上下左右走,变成6种操作,再记录路径,注意vis标记
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a,b,c,vis[105][105],d[105],flag;
struct node
{
int a,b,k,op,pre;
} no,ne,q[20005];
void output(int pre)
{
int tot=0;
while(pre)
{
d[tot++]=pre;
pre=q[pre].pre;
}
for(int i=tot-1;i>=0;i--)
{
int op=q[d[i]].op;
if(op==1) printf("FILL(1)\n");
else if(op==2) printf("FILL(2)\n");
else if(op==3) printf("DROP(1)\n");
else if(op==4) printf("DROP(2)\n");
else if(op==5) printf("POUR(1,2)\n");
else if(op==6)printf("POUR(2,1)\n");
}
}
void bfs()
{
memset(vis,0,sizeof(vis));
no.a=0,no.b=0,no.k=0,no.op=0,no.pre=0;
int head,tail;
head=tail=0;
vis[0][0]=1;
q[tail]=no;
tail++;
while(head<tail)
{
no=q[head];
head++;
if(no.k>100)
return ;
for(int i=1; i<=6; i++)
{
if(i==1) ne.a=a,ne.b=no.b;
else if(i==2) ne.a=no.a,ne.b=b;
else if(i==3) ne.a=0,ne.b=no.b;
else if(i==4) ne.a=no.a,ne.b=0;
else if(i==5)
{
int k=b-no.b;
if(k>=no.a) ne.a=0,ne.b=no.b+no.a;
else ne.a=no.a-k,ne.b=b;
}
else if(i==6)
{
int k=a-no.a;
if(k>=no.b) ne.b=0,ne.a=no.a+no.b;
else ne.b=no.b-k,ne.a=a;
}
if(!vis[ne.a][ne.b])
{
vis[ne.a][ne.b]=1;
ne.k=no.k+1;
ne.op=i;
ne.pre=head-1;
q[tail]=ne;
tail++;
if(ne.a==c||ne.b==c)
{
flag=1;
printf("%d\n",ne.k);
output(tail-1);
return ;
}
}
}
}
}
int main()
{
while(~scanf("%d%d%d",&a,&b,&c))
{
flag=0;
bfs();
if(!flag) printf("impossible\n");
}
return 0;
}