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 poti), or the poti is empty (and all its contents have been moved to the potj).
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 andC≤max(A,B).
Output
The first line of the output must contain the length of the sequence of operationsK. The followingK 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)
题目意思:给出两个杯子容积,初始都为空杯子,给出目标水量,可以执行一些操作,分别是倒空一个杯子,
倒满一个杯子,和将一个杯子的水倒到另一个中,问得到目标水量要进行至少多少次以及每次都是什么并输出,
FILL(1)表示倒满1杯子,POUR(2,1)表示将2杯子里的水倒进1杯子中,DROP(1)表示倒空1杯子。
如果做不到,输出impossible。
这道题典型套BFS:给定初始状态跟目标状态,要求从初始状态到目标状态的最短路。
本体为广度优先生成树,每次对六种操作进行广度搜索,用二维数组进行状态是否出现过的标记,并记录每次出现的节点的父节点,最后用递归进行输出。AC代码:
#include<stdio.h>
#include<string.h>
#include<queue>
#include<stdlib.h>
using namespace std;
int A,B,C;
struct node{
int v1,v2;
int step;
int type; //操作类别:0代表倒完杯1,1代表倒完杯2,2代表装满杯1,3代表装满杯2,
//4代表杯1向杯2倒水,5代表杯2向杯1倒水
node *last; //指向它的上一个状态
};
int vis[105][105];
void operate(int i,node *s,node *e){ //6种操作
e->type=i;
if(i==0){
e->v1=0;
e->v2=s->v2;
}
else if(i==1){
e->v2=0;
e->v1=s->v1;
}
else if(i==2){
e->v1=A;
e->v2=s->v2;
}
else if(i==3){
e->v2=B;
e->v1=s->v1;
}
else if(i==4){
if(s->v1>=(B-s->v2)){
e->v2=B;
e->v1=s->v1-(B-s->v2);
}
else{
e->v1=0;
e->v2=s->v2+s->v1;
}
}
else {
if(s->v2>=(A-s->v1)){
e->v1=A;
e->v2=s->v2-(A-s->v1);
}
else{
e->v2=0;
e->v1=s->v2+s->v1;
}
}
e->last=s;
e->step=s->step+1;
}
node* Bfs(){
int i;
memset(vis,0,sizeof(vis));
queue<node *>q;
vis[0][0]=1;
node *s;
s=(node *)malloc(sizeof(node));
s->v1=0;
s->v2=0;
s->type=-1;
s->step=0;
s->last=NULL;
q.push(s);
while(!q.empty()){
s=q.front();
q.pop();
if(s->v1==C||s->v2==C)
return s;
for(i=0;i<6;i++){
node *e;
e=(node *)malloc(sizeof(node));
operate(i,s,e);
if(vis[e->v1][e->v2])continue;
vis[e->v1][e->v2]=1;
q.push(e);
}
}
return NULL; //不能做到
}
void Output(node *t){ //递归地输出倒水的步骤
if(t->last==NULL)return;
Output(t->last);
if(t->type==0)printf("DROP(1)\n");
else if(t->type==1)printf("DROP(2)\n");
else if(t->type==2)printf("FILL(1)\n");
else if(t->type==3)printf("FILL(2)\n");
else if(t->type==4)printf("POUR(1,2)\n");
else printf("POUR(2,1)\n");
}
int main()
{
while(scanf("%d %d %d",&A,&B,&C)!=EOF){
if(!Bfs())
{
printf("impossible\n");
continue;
}
printf("%d\n",Bfs()->step);
Output(Bfs());
}
return 0;
}