Pots
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
On the first and only line are the numbers A, B, andC. 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 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’.
Sample Input
3 5 4Sample Output
6FILL(2)POUR(2,1)DROP(1)POUR(2,1)FILL(2) POUR(2,1)题意:给出两个容积分别为 a 和 b的pot,按照以下三种操作方式,求出能否在一定步数后,使者两个pot的其中一个的水量为c。
1.FILL(i):将ipot倒满水。
2.DROP(i):将ipot倒空水。
3.POUR(i,j): 将ipot的水倒到jpot上,直至要么ipot为空,要么jpot为满。
直接BFS求解,将步骤存到结构体内即可:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cstring>
using namespace std;
int A,B,C;
int flag[101][101];
char str[6][10]= {"FILL(1)","FILL(2)","POUR(2,1)","POUR(1,2)","DROP(1)","DROP(2)"};
struct node
{
int num1,num2;
string a;
int step;
};
void bfs()
{
node p,temp;
int i;
p.num1=0;
p.num2=0;
p.step=0;
p.a="";
queue<node>Q;
while(!Q.empty())
Q.pop();
Q.push(p);
while(!Q.empty())
{
p=Q.front();
Q.pop();
if(flag[p.num1][p.num2])
continue;
else
flag[p.num1][p.num2]=1;
if(p.num1==C||p.num2==C)
{
printf("%d\n",p.step);
int j;
for(j=0; j<p.step; j++)
{
printf("%s\n",str[(p.a[j])-'0']);
}
return;
}
for(i=0; i<4; i++)
{
temp=p;
temp.step=p.step+1;
if(i==0)
{
if(temp.num1==0)
{
temp.num1=A;
temp.num2=p.num2;
temp.a=p.a+'0';
Q.push(temp);
}
if(temp.num2==0)
{
temp.num2=B;
temp.num1=p.num1;
temp.a=p.a+'1';
Q.push(temp);
}
}
if(i==1)
{
if(temp.num1!=0)
{
temp.num1=0;
temp.num2=p.num2;
temp.a=p.a+'4';
Q.push(temp);
}
if(temp.num2!=0)
{
temp.num2=0;
temp.num1=p.num1;
temp.a=p.a+'5';
Q.push(temp);
}
}
if(i==2)
{
if(temp.num1!=0 && temp.num2!=B)
{
int dd=B-temp.num2;
if(temp.num1>=dd)
{
temp.num2=B;
temp.num1-=dd;
}
else
{
temp.num2+=temp.num1;
temp.num1=0;
}
temp.a=p.a+'3';
Q.push(temp);
}
}
if(i==3)
{
if(temp.num2!=0 && temp.num1!=A)
{
int dd=A-temp.num1;
if(temp.num2>=dd)
{
temp.num1=A;
temp.num2-=dd;
}
else
{
temp.num1+=temp.num2;
temp.num2=0;
}
temp.a=p.a+'2';
Q.push(temp);
}
}
}
}
printf("impossible\n");
}
int main()
{
while(scanf("%d%d%d",&A,&B,&C)!=EOF)
{
memset(flag,0,sizeof(flag));
bfs();
}
return 0;
}