题目链接 点击打开链接
Time Limit: 1000MS | Memory Limit: 65536KB | 64bit IO Format: %I64d & %I64u |
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 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)
#include<iostream>
#include<cstring>
#include<queue>
#include<stdio.h>
using namespace std;
struct AB
{
int pre;
int a,b;
int c;
};
AB q[10000];
int head,tail;
int A,B,C;
int aa,bb;
bool visit[101][101];
void FILL(int i)
{
if(i==1)
aa=A;
else bb=B;
}
void POUR(int i,int j)
{
int a=aa,b=bb;
if(i==1)
{
if(a+b>B)
{
bb=B;
aa=a+b-B;
}
else
{
bb=a+b;
aa=0;
}
}
else
{
if(a+b>A)
{
aa=A;
bb=a+b-A;
}
else
{
aa=a+b;
bb=0;
}
}
}
void DROP(int i)
{
if(i==1)
aa=0;
else bb=0;
}
void operate(int i)
{
switch(i)
{
case 0:
{
FILL(1);
break;
}
case 1:
{
FILL(2);
break;
}
case 2:
{
POUR(1,2);
break;
}
case 3:
{
POUR(2,1);
break;
}
case 4:
{
DROP(1);
break;
}
case 5:
{
DROP(2);
break;
}
}
}
void out(int i)
{
switch(i)
{
case 0:
{
cout<<"FILL(1)"<<endl;
break;
}
case 1:
{
cout<<"FILL(2)"<<endl;
break;
}
case 2:
{
cout<<"POUR(1,2)"<<endl;
break;
}
case 3:
{
cout<<"POUR(2,1)"<<endl;
break;
}
case 4:
{
cout<<"DROP(1)"<<endl;
break;
}
case 5:
{
cout<<"DROP(2)"<<endl;
break;
}
}
}
int BFS()
{
head=tail=0;
q[tail].a=0;
q[tail].b=0;
q[tail++].pre=-1;
visit[0][0]=true;
while(1)
{
if(head==tail)
{
return 0;
}
if(q[head].a==C||q[head].b==C)
{
return head;
}
for(int i=0; i<6; i++)
{
aa=q[head].a;
bb=q[head].b;
operate(i);
if(!visit[aa][bb])
{
visit[aa][bb]=true;
q[tail].pre=head;
q[tail].a=aa;
q[tail].b=bb;
q[tail++].c=i;
}
}
head++;
}
}
int main()
{
while(scanf("%d %d %d",&A,&B,&C)!=EOF)
{
memset(visit,false,sizeof(visit));
int t=BFS();
int way[10000],n=0;
if(!t)
cout<<"impossible"<<endl;
else
{
while(q[t].pre!=-1)
{
way[n++]=t;
t=q[t].pre;
}
cout<<n<<endl;
while(n--)
{
out(q[way[n]].c);
}
}
}
return 0;
}