本文主要是介绍Pots POJ - 3414(bfs),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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)
虽然不能打acm了,但是还是要补一下之前的坑。
直接按着状态广搜,标记这个状态出没出现过,出现过就不要向下扩展了。没出现就向下扩展。
代码如下:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#define ll long long
using namespace std;char ss[6][20]={"FILL(2)","FILL(1)","POUR(2,1)","POUR(1,2)","DROP(1)","DROP(2)"};
struct node{int a;int b;string s;node(int x,int y,string z){a=x,b=y,s=z;}
};
int a,b,c;inline void bfs()
{queue<node> q;map<pair<int,int>,bool> mp;q.push(node(0,0,""));mp[make_pair(0,0)]=0;while(q.size()){node bb=q.front();q.pop();if(bb.a==c||bb.b==c){printf("%d\n",bb.s.length());for(int i=0;i<bb.s.length();i++) {int x=bb.s[i]-'0';printf("%s\n",ss[x]);}return ;}if(mp[make_pair(bb.a,bb.b)]) continue;else mp[make_pair(bb.a,bb.b)]=1;if(bb.a<=a) {q.push(node(a,bb.b,bb.s+"1"));int x=a-bb.a;if(bb.b>0&&x){ if(x>=bb.b) q.push(node(bb.a+bb.b,0,bb.s+"2"));else q.push(node(a,bb.b-x,bb.s+"2"));}}if(bb.b<=b) {q.push(node(bb.a,b,bb.s+"0"));int x=b-bb.b;if(bb.a>0&&x){if(x>=bb.a) q.push(node(0,bb.b+bb.a,bb.s+"3"));else q.push(node(bb.a-x,b,bb.s+"3"));}}if(bb.a) q.push(node(0,bb.b,bb.s+"4"));if(bb.b) q.push(node(bb.a,0,bb.s+"5"));}printf("impossible\n");
}
int main()
{while(~scanf("%d%d%d",&a,&b,&c)){bfs();}return 0;
}
喜欢算法,不一定非要打比赛,当个乐趣消遣消遣也是不错的。
努力加油a啊,(o)/~
这篇关于Pots POJ - 3414(bfs)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!