Pots
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 20 Accepted Submission(s) : 12
Special Judge
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.
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).
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’.
3 5 4
6 FILL(2) POUR(2,1) DROP(1) POUR(2,1) FILL(2) POUR(2,1)
<pre name="code" class="cpp">#include<iostream>
#include<map>
#include<string>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
#define maxn 105
bool vis[maxn][maxn];
int A, B, C;
struct State
{
int a, b;
int dir, pre;
}Q[maxn*maxn], Try, u;
int flag;
int head, tail;
void Visit()
{
if (vis[Try.a][Try.b] == false)
{ //需要记录路径就不能用STL的queue了
Q[tail++] = Try; //(如果需要记录路径,则先进队列再访问比较方便查找路径)
if (Try.a == C || Try.b == C)
{
flag = 1;
return;
}
vis[Try.a][Try.b] = true;
}
}
void BFS()
{
head = tail = 0;
Try.a = 0; Try.b = 0; Try.pre = -1;
Visit();
if (flag) return;
while (head < tail)
{
u = Q[head++];
for (int j = 0; j < 6; j++) //共6种操作
{
if (flag) return;
Try.dir = j; Try.pre = head - 1;
switch (j)
{
case 0:
Try.a = A; Try.b = u.b;
Visit();
break;
case 1:
Try.a = u.a; Try.b = B;
Visit();
break;
case 2:
Try.a = 0; Try.b = u.b;
Visit();
break;
case 3:
Try.a = u.a; Try.b = 0;
Visit();
break;
case 4:
if (B >= u.b + u.a)
{
Try.a = 0;
Try.b = u.b + u.a; //(注意每个新点的值都从父状态获得,最初又写错了)
}
else
{
Try.b = B;
Try.a = u.a - (B - u.b);
}
Visit();
break;
case 5:
if (A >= u.a + u.b)
{
Try.b = 0;
Try.a = u.a + u.b;
}
else
{
Try.a = A;
Try.b = u.b - (A - u.a);
}
Visit();
break;
}
}
}
}
int main()
{
scanf("%d%d%d", &A, &B, &C);
memset(vis, false, sizeof(vis));
flag = 0;
BFS();
if (flag)
{
int p, ans[100000];
int top = 0;
p = tail - 1;
while (Q[p].pre != -1) //当p所指的不是起点状态(最初写错了)
{
ans[top++] = Q[p].dir;
p = Q[p].pre;
}
printf("%d\n", top);
char str[6][10] = { "FILL(1)", "FILL(2)", "DROP(1)", "DROP(2)", "POUR(1,2)", "POUR(2,1)" };
for (int i = top - 1; i >= 0; i--)
printf("%s\n", str[ans[i]]);
}
else
printf("impossible\n");
return 0;
}