Pots
Time Limit: 1000MS Memory Limit: 65536KB
Problem 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. If the desired result can’t be achieved, the first and only line of the file must contain the word ‘impossible’.
Example Input
3 5 4
Example Output
6
Hint
FILL(2)
POUR(2,1)
DROP(1)
POUR(2,1)
FILL(2)
POUR(2,1)
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct node
{
int a, b;
int step;
}ST;
ST s[500000], t;//s[]数组模拟队列
int map[1000][1000], head, last, n, m, k;//map[][]标记这种情况出现没出现过
void bfs(int A, int B)
{
if(head >= last)//所有可能的情况都找不到
{
printf("impossible\n");
return ;
}
if(A == k || B == k)//两个容器的容量谁等于第三个(k)就输出
{
printf("%d\n", s[head].step);
return ;
}
t = s[head++];//出队列
int i;
for(i = 0; i < 6; i++)//下一步两个容器的容量的可能性
{
if(i == 0 && !map[A][m])//第一个不变,第二个装满
{
s[last].a = A;
s[last].b = m;
s[last++].step = t.step + 1;//下一步等于上一次的步数次数加一
map[A][m] = 1;
}
else if(i == 1 && !map[n][B])//第二个不变,第一个装满
{
s[last].a = n;
s[last].b = B;
s[last++].step = t.step + 1;
map[n][B] = 1;
}
else if(i == 2 && !map[0][B])//第二个不变,倒掉第一个
{
s[last].a = 0;
s[last].b = B;
s[last++].step = t.step + 1;
map[0][B] = 1;
}
else if(i == 3 && !map[A][0])//第一个不变,倒掉第二个
{
s[last].a = A;
s[last].b = 0;
s[last++].step = t.step + 1;
map[A][0] = 1;
}
else if(i == 4)//B倒入A 又分为两种情况
{
if(A + B > n && !map[n][A + B - n])//A满 B还剩下
{
s[last].a = n;
s[last].b = A + B - n;
s[last++].step = t.step + 1;
map[n][A + B - n] = 1;
}
else if(A + B <= n && !map[A + B][0])//B没有了,全倒入A
{
s[last].a = A + B;
s[last].b = 0;
s[last++].step = t.step + 1;
map[A + B][0] = 1;
}
}
else if(i == 5)
{
if(A + B > m && !map[A + B - m][m])//B满,A还剩下
{
s[last].a = A + B - m;
s[last].b = m;
s[last++].step = t.step + 1;
map[A + B - m][m] = 1;
}
else if(A + B <= m && !map[0][A + B])//A没有了,全倒入B
{
s[last].a = 0;
s[last].b = A + B;
s[last++].step = t.step + 1;
map[0][A + B] = 1;
}
}
}
bfs(s[head].a, s[head].b);//继续调用队列的开头
}
int main()
{
while(~scanf("%d %d %d", &n, &m, &k))//三个容器的体积
{
memset(map, 0, sizeof(map));
head = last = 0;
map[0][0] = 1;//最开始的情况是两个容器都是空
s[last].a = 0;//存入数组
s[last].step = 0;//次数0
s[last++].b = 0;
bfs(s[head].a, s[head].b);//调用BFS
}
return 0;
}