这道题的题意是:给你两个空杯子,容量为a和b升。只用这两个杯子,在水充足的条件下倒出c升的水、、
一共有六种操作:1、把a倒满;2、把b倒满;3、把a倒空;4、把b倒空;5、把b倒入a中;6、把a倒入b中。
根据这六种情况进行BFS,但是这道题记录路径很麻烦,用了邻接表进行的记录;在hash输出就行了。
感觉不错的一道题。
Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 8295 | Accepted: 3524 | Special Judge |
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 <stdio.h>
#include <string.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int v[150][150], step[12000];
int a, b, c, l, r;
char s[7][10] = {" ", "FILL(1)", "FILL(2)", "DROP(1)", "DROP(2)", "POUR(2,1)", "POUR(1,2)"};
struct node
{
int x, y, d, front;
} f[10500];
int _min(int xx, int yy)
{
if(xx > yy)
return yy;
return xx;
}
void slove(int xx, int yy, int ss)
{
if(v[xx][yy])
return;
v[xx][yy] = 1;
f[r].x = xx, f[r].y = yy, f[r].d = ss, f[r++].front = l;
}
void _printf()
{
int i, t = 0;
while(l!= 0)
{
step[t++] = f[l].d;
l = f[l].front;
}
printf("%d\n",t);
for(i = t-1; i >= 0; i--)
printf("%s\n",s[step[i]]);
}
void bfs()
{
f[0].x = 0,f[0].y = 0;
v[0][0] = 1;
l = 0, r = 1;
while(l != r)
{
if(f[l].x == c || f[l].y == c)
{
_printf();
return;
}
int xx, yy;//把1倒满
xx = a;
yy = f[l].y;
slove(xx, yy, 1);
xx = f[l].x;//把2倒满
yy = b;
slove(xx, yy, 2);
xx = 0;//把1清空
yy = f[l].y;
slove(xx, yy, 3);
xx = f[l].x;//把2清空
yy = 0;
slove(xx, yy, 4);
xx = f[l].x + _min(a-f[l].x , f[l].y);//把2倒入1
yy = f[l].y - _min(a-f[l].x , f[l].y);
slove(xx, yy, 5);
xx = f[l].x - _min(b-f[l].y , f[l].x);//把1倒入2
yy = f[l].y + _min(b-f[l].y , f[l].x);
slove(xx, yy, 6);
l++;
}
if(l >= r)
printf("impossible\n");
}
int main()
{
scanf("%d %d %d",&a, &b, &c);
memset(v , 0 , sizeof(v));
bfs();
return 0;
}