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)
大意:给定两个杯子的容量,有六种操作,通过操作使得两个被子其中一个杯子的水等于待输入值C,并输出最少操作次数和操作名称
#include<iostream>
#include<stdio.h>
#include<queue>
#include<stack>
#include<string>
#include<string.h>
using namespace std;
string aa[6]={"FILL(1)","FILL(2)","DROP(1)","DROP(2)",
"POUR(1,2)","POUR(2,1)"};
struct node{
int x,y,id;//x,y表示其父节点的坐标,id表示当前所走的类型,
}nd[300][300];
typedef pair<int,int> p;
queue<p>q;
stack<int>s;
int vst[300][300];
int a,b,c;
void bfs(){
nd[0][0].x=-1;
nd[0][0].y=-1;
nd[0][0].id=-1;
vst[0][0]=1;
q.push(make_pair(0,0));
while(!q.empty()){
p now=q.front();
p next;
q.pop();
int j,k;
for(int i=0;i<6;i++){
switch(i){
case 0:next.first=a;
next.second=now.second;
break;
case 1:next.first=now.first;
next.second=b;
break;
case 2:next.first=0;
next.second=now.second;
break;
case 3:next.first=now.first;
next.second=0;
break;
case 4:j=now.first;
k=now.second;
if(j<=(b-k)){
next.first=0;
next.second=now.second+j;
}else{
next.first=j-(b-now.second);
next.second=b;
}
break;
case 5:j=now.second;
k=now.first;
if(j<=(a-k)){
next.first=now.first+j;
next.second=0;
}else{
next.first=a;
next.second=j-(a-now.first);
}
break;
}
if(!vst[next.first][next.second]){
vst[next.first][next.second]=1;
nd[next.first][next.second].id=i;
nd[next.first][next.second].x=now.first;
nd[next.first][next.second].y=now.second;
if(next.first==c||next.second==c){
int idd=nd[next.first][next.second].id;
int xx=nd[next.first][next.second].x;
int yy=nd[next.first][next.second].y;
int x1,y1;
while(xx!=0||yy!=0){
s.push(idd);
x1=nd[xx][yy].x;
y1=nd[xx][yy].y;
idd=nd[xx][yy].id;
xx=x1;
yy=y1;
}
s.push(idd);
cout<<s.size()<<endl;
while(!s.empty()){
cout<<aa[s.top()]<<endl;
s.pop();
}
return;
}
q.push(next);
}
}
}
cout<<"impossible"<<endl;
return;
}
int main(){
memset(vst,0,sizeof(vst));
scanf("%d%d%d",&a,&b,&c);
bfs();
return 0;
}