题目
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.
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)
题意
给你两个不同体积的瓶子(n,m)和一个瓶子要出现的体积(t),求实现过程
FILL(i)把i装满
POUR(i,j)把i中的水倒给j
DROP(i)把i中的水倒掉
代码实现
#include"stdio.h"
#include"queue"
#include"string.h"
#include"algorithm"
using namespace std;
int b[120][120],m,n,t;
struct dd
{
int x,y,z,s;
} t1,t2,f[120][120];
queue<dd>q;
void print(dd xx)
{
if(!xx.x&&!xx.y)
return;
print(f[xx.x][xx.y]);
if(f[xx.x][xx.y].z==0)printf("FILL(1)\n");
else if(f[xx.x][xx.y].z==1)printf("FILL(2)\n");
else if(f[xx.x][xx.y].z==2)printf("DROP(1)\n");
else if(f[xx.x][xx.y].z==3)printf("DROP(2)\n");
else if(f[xx.x][xx.y].z==4)printf("POUR(1,2)\n");
else if(f[xx.x][xx.y].z==5)printf("POUR(2,1)\n");
}
void bfs()
{
t1.x=0;
t1.y=0;
t1.s=0;
b[0][0]=1;
f[0][0]=t1;
q.push(t1);
while(!q.empty())
{
t1=q.front();
q.pop();
for(int i=0; i<6; i++)
{
t2.x=t1.x;
t2.y=t1.y;
if(i==0)t2.x=n;
else if(i==1)t2.y=m;
else if(i==2)t2.x=0;
else if(i==3)t2.y=0;
else if(i==4)//x->y
{
if( (t2.x+t2.y)>=m)//两个瓶子里的水大于等于要倒给瓶子的容积
{
t2.x=t2.y+t2.x-m;
t2.y=m;
}
else//两个瓶子里的水小于要倒给瓶子的容积
{
t2.y=t2.y+t2.x;
t2.x=0;
}
}
else if(i==5)//y->x
{
if((t2.x+t2.y)>=n)//两个瓶子里的水大于等于要倒给瓶子的容积
{
t2.y=t2.x+t2.y-n;
t2.x=n;
}
else//两个瓶子里的水小于要倒给瓶子的容积
{
t2.x=t2.x+t2.y;//
t2.y=0;//顺序不能写反
}
}
// printf("%d %d$$$%d %d\n",t1.x,t1.y,t2.x,t2.y);
if(b[t2.x][t2.y]==1)continue;
b[t2.x][t2.y]=1;
t2.s=t1.s+1;
f[t2.x][t2.y]=t1;
f[t2.x][t2.y].z=i;
q.push(t2);
if(t2.x==t||t2.y==t)
{
printf("%d\n",t2.s);
print(t2);
return;
}
}
}
printf("impossible");
return;
}
int main()
{
int i,j,k;
scanf("%d%d%d",&n,&m,&t);
bfs();
return 0;
}
、、、
、、、