Pots
Description
You are given two pots, having the volume of A and B liters respectively. The following operations can be performed:
1.FILL(i) fill the pot i (1 ≤ i ≤ 2) from the tap;
2.DROP(i) empty the pot i to the drain;
3.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)
思路
用BFS枚举6个状态。
记录路径有点麻烦,当时也没想到,压入队列的根节点都有前驱,前面的已经记录过了,枚举下一个结点,需要将当前的地址复制给下一个的,这样前面已经记录过的数据接着使用。
AC代码
#include<cstdio>
#include<iostream>
#include<string>
#include<queue>
#include<algorithm>
#define IOS std::ios::sync_with_stdio(false)
using namespace std;
const int maxn = 110;
struct cup{
int a, b;
int step;
string s[maxn];
};
bool vis[maxn][maxn];
bool bfs(int a, int b, int c){
queue<cup> q;
cup tmp;
tmp.a = 0;
tmp.b = 0;
tmp.step = 0;
vis[0][0] = true;
q.push(tmp);
while(!q.empty()){
cup now = q.front(); q.pop();
for (int i = 1; i <= 6; ++i){
//需要赋值,不然前面的数据将会被清空。
tmp = now;
switch(i){
//当a杯子中的水没满才可以加
case 1:{
if (now.a != a){
tmp.a = a;
tmp.step += 1;
tmp.s[tmp.step] = "FILL(1)";
}
break;
}
//当b杯子中的水没满才就可以加
case 2:{
if (now.b != b){
tmp.b = b;
tmp.step += 1;
tmp.s[tmp.step] = "FILL(2)";
}
break;
}
//当a杯子中的水不为空才倒
case 3:{
if (now.a != 0){
tmp.a = 0;
tmp.step += 1;
tmp.s[tmp.step] = "DROP(1)";
}
break;
}
//当b杯子中的水不为空才倒
case 4:{
if (now.b != 0){
tmp.b = 0;
tmp.step += 1;
tmp.s[tmp.step] = "DROP(2)";
}
break;
}
//a往b倒水,a是空的且b不是满的,能否把b装满
case 5:{
if (now.a != 0 && now.b != b){
if (now.a > b - now.b){
tmp.a = now.a - (b - now.b);
tmp.b = b;
} else{
tmp.a = 0;
tmp.b = now.a + now.b;
}
tmp.step += 1;
tmp.s[tmp.step] = "POUR(1,2)";
}
break;
}
//b往a倒水 b是空的且a不是满的,能否把a装满
case 6:{
if (now.a != a && now.b != 0){
if (now.b > a - now.a){
tmp.a = a;
tmp.b = now.b - (a - now.a);
} else {
tmp.a = now.a + now.b;
tmp.b = 0;
}
tmp.step += 1;
tmp.s[tmp.step] = "POUR(2,1)";
}
break;
}
}
if (tmp.a == c || tmp.b == c){
cout << tmp.step << endl;
for (int i = 1; i <= tmp.step; ++i){
cout << tmp.s[i] << endl;
}
return true;
}
if (vis[tmp.a][tmp.b]) continue;
vis[tmp.a][tmp.b] = true;
q.push(tmp);
}
}
return false;
}
void solve(){
int a, b, c;
cin >> a >> b >> c;
if(!bfs(a, b, c)){
cout << "impossible" << endl;
}
}
int main(){
IOS;
solve();
return 0;
}