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 jis 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 operationsK. 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)
思路: 求最少倒水次数,可以想象,两个杯子,每次6种状态,1 a->full 2 b->full 3 a->b 4 b->a 5 a->0 6 b->0 每次都是相似的状态,所以可以进行广搜。
#include <cstdio> #include <queue> #include <map> #include <stack> #include <algorithm> #include <iostream> using namespace std; int mk[110][110]; typedef struct node{ int a,b; int way;//倒水方式 int t; //记录时间 }node; node path[110][110]; //记录路径,记录自己从哪里来,最后入栈倒着打印。 void showAns(node nd) { printf("%d\n",nd.t); stack <int> s; s.push(nd.way); int x = nd.a,y = nd.b; while(path[x][y].way) { s.push(path[x][y].way); int x_ = path[x][y].a; int y_ = path[x][y].b; x = x_,y = y_; } while(!s.empty()) { int type = s.top(); s.pop(); switch(type){ case 1 : printf("FILL(1)\n");break; case 2 : printf("FILL(2)\n");break; case 3 : printf("POUR(1,2)\n");break; case 4 : printf("POUR(2,1)\n");break; case 5 : printf("DROP(1)\n");break; case 6 : printf("DROP(2)\n");break; } } } void bfs(int a,int b,int c) { queue<node> q; node tmp; tmp.a = tmp.b =tmp.way = tmp.t = 0; mk[0][0] = 1; q.push(tmp); while(!q.empty()) { tmp = q.front(); q.pop(); node nd; for(int i = 1; i <= 6; i++) { nd.way = i,nd.t = tmp.t+1; switch(i){ //1 a->full 2 b->full 3 a->b 4 b->a 5 a->0 6 b->0 case 1: nd.a = a;nd.b = tmp.b; break; case 2: nd.b = b;nd.a = tmp.a; break; case 3: nd.a = tmp.a-(min(b,tmp.a+tmp.b)-tmp.b);nd.b = min(b,tmp.a+tmp.b);break; case 4: nd.b = tmp.b-(min(a,tmp.a+tmp.b)-tmp.a);nd.a = min(a,tmp.a+tmp.b);break; case 5: nd.a = 0;nd.b = tmp.b; break; case 6: nd.b = 0;nd.a = tmp.a; break; }//注意3,4 有可能满。 if(nd.a == c || nd.b == c) { path[nd.a][nd.b] = tmp; showAns(nd); return; } if(!mk[nd.a][nd.b]) { path[nd.a][nd.b] = tmp; mk[nd.a][nd.b] = 1; q.push(nd); } } } printf("impossible\n"); } int main() { int a,b,c; cin >>a>>b>>c; bfs(a,b,c); return 0; }