传送门POJ3414
描述
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’.
样例
Input3 5 4
Output6FILL(2)POUR(2,1)DROP(1)POUR(2,1)FILL(2)POUR(2,1)
题解
题意:有两个杯子,每次可以对他们进行3种操作:FILL(i):装满i;DROP(i):倒掉i中的水;POUR(i,j):从i往j倒水;要使得某个杯子中有c升水,求最少操作次数以及对应步骤,输出任意路径bfs,字符串映射记录路径
Code
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566#include<iostream>#include<cstring>#include<queue>#define INIT(a,b) memset(a,b,sizeof(a))#define LL long longusing namespace std;const int inf=0x3f3f3f3f;const int N=1e2+7;const int mod=1e9+7;struct node{ int x,y,time; string op;};string ops[7]={"","FILL(1)","FILL(2)","POUR(1,2)","POUR(2,1)","DROP(1)","DROP(2)"};int a,b,c,vis[N][N];void bfs(){ queue<node> que; que.push((node){0,0,0,"0"}); vis[0][0]=1; while(!que.empty()){ node q=que.front();que.pop(); if(q.x==c||q.y==c){ cout<<q.time<<endl; for(int i=0;i<q.op.size();i++){ if(q.op[i]!='0') cout<<ops[q.op[i]-'0']<<endl; } return ; } if(q.x!=a && !vis[a][q.y]) { vis[a][q.y]=1; que.push((node){a,q.y,q.time+1,q.op+"1"}); } if(q.y!=b && !vis[q.x][b]) { vis[q.x][b]=1; que.push((node){q.x,b,q.time+1,q.op+"2"}); } if(q.x>0 && !vis[0][q.y]){ vis[0][q.y]=1; que.push((node){0,q.y,q.time+1,q.op+"5"}); } if(q.y>0 && !vis[q.x][0]){ vis[q.x][0]=1; que.push((node){q.x,0,q.time+1,q.op+"6"}); } int can=min(q.x,b-q.y); if(can && !vis[q.x-can][q.y+can]){ vis[q.x-can][q.y+can]=1; que.push((node){q.x-can,q.y+can,q.time+1,q.op+"3"}); } can=min(q.y,a-q.x); if(can && !vis[q.x+can][q.y-can]){ vis[q.x+can][q.y-can]=1; que.push((node){q.x+can,q.y-can,q.time+1,q.op+"4"}); } } cout<<"impossible"<<endl;}int main(){ ios::sync_with_stdio(false); cin.tie(0); cin>>a>>b>>c; bfs(); return 0;}