Pots
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
There are multiple test cases.
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)
Author
#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)//成功 { printf("%d\n",s[head].step); return ; } t = s[head++]; //出队列 int i; for(i = 0;i < 6;i++) //六种可能情况 { if(i == 0&&map[A][m]==0)//第一个不变,第二个装满 { s[last].a = A; s[last].b = m; s[last].step = t.step+1; //步数加一 last++;//进栈 map[A][m]=1; } else if(i == 1&&map[n][B]==0)//第二个不变,第一个装满 { s[last].a = n; s[last].b = B; s[last].step=t.step+1; last++; map[n][B] = 1; } else if(i == 2&&map[0][B]==0)//第二个不变,第一个倒掉 { s[last].a=0; s[last].b=B; s[last].step = t.step+1; last++; map[0][B] = 1; } else if(i == 3&&map[A][0]==0)//第一个不变,第二个倒掉 { s[last].a = A; s[last].b = 0; s[last].step= t.step+1; last++; 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; last++; 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; last++; map[A + B][0] = 1; } } else if(i == 5) //A 倒入B { 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; last++; 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; last++; map[0][A + B] = 1; } } } bfs(s[head].a,s[head].b); //遍历队列开头 } int main() { while(scanf("%d%d%d",&n,&m,&k) != EOF)//三个容器体积 { memset(map,0,sizeof(map)); head = last = 0; map[0][0] = 1;//初始为空 s[last].a = 0; s[last].step = 0; s[last++].b=0; bfs(s[head].a,s[head].b); } return 0; }