题目链接:http://poj.org/problem?id=3414
Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 14306 | Accepted: 6033 | 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)
Source
#include <cstdio> #include <cstring> #include <iostream> #include <cmath> #include<vector> #include<queue> #include<algorithm> using namespace std; typedef long long LL; const int maxn=107; const int INF=0x3f3f3f3f; int a, b, c, f; int vis[maxn][maxn]; char str[6][10]= {"FILL(1)", "FILL(2)", "POUR(1,2)", "POUR(2,1)", "DROP(1)", "DROP(2)"};///步骤对应的动作 struct node { int x, y, step; char s[maxn]; }; void bfs() { memset(vis, 0, sizeof(vis)); node p, q; queue<node>Q; p.x=0; p.y=0; p.step=0; p.s[0]='0'; Q.push(p); vis[p.x][p.y]=1; while(!Q.empty()) { q=Q.front(); Q.pop(); if(q.x==c || q.y==c) { f=1; printf("%d ", q.step); for(int i=1; i<=q.step; i++) printf("%s ", str[q.s[i]-'0']); return ; } for(int i=0; i<6; i++) { p.step=q.step+1;///记录你运行到第几步 p.x=p.y=0; strcpy(p.s, q.s); p.s[p.step]=i+'0';///第q.step步选择的步骤 if(i==0&&q.x!=a)///将第一个杯子加满,那么此杯子里面水肯定是不满的 { p.x=a; p.y=q.y; } else if(i==1&&q.y!=b)///将第二个杯子加满,那么此杯子里面水肯定是不满的 { p.x=q.x; p.y=b; } else if(i==2&&q.x&&q.y!=b)///将1往2加 ,那么要保证1中必须有水,2中必须不满才能加 { if(q.x+q.y<=b)///1可以全部加入2中 { p.x=0; p.y=q.x+q.y; } else///不能全部加入,还剩下 { p.x=q.x+q.y-b; p.y=b; } } else if(i==3&&q.y&&q.x!=a)///将2往1加 ,那么要保证2中必须有水,1中必须不满才能加 { if(q.x+q.y<=a)///2可以全部加入1中 { p.x=q.x+q.y; p.y=0; } else///不能全部加入,还剩下 { p.x=a; p.y=q.x+q.y-a; } } else if(i==4 && q.x)///将1清0 ,那么1之前一定不等于0 { p.x=0; p.y=q.y; } else if(i==5 && q.y) { p.x=q.x; p.y=0; } if(!vis[p.x][p.y])///没有标记的入队 { vis[p.x][p.y]=1; Q.push(p); } } } } int main() { while(~scanf("%d %d %d", &a, &b, &c)) { f=0; bfs(); if(!f) puts("impossible"); } return 0; }