点此进入题目链接:POJ 3414
思路 :这题给 给这个 题目一样 HDU - 1495 非常可乐 一样 只不过需要记录路径
AC:代码
#include<iostream>
#include<cstring>
#include<queue>
#include<stack>
#include<math.h>
#include<algorithm>
#include<vector>
#include<string.h>
using namespace std;
const int maxn = 101;
bool inq[maxn][maxn] = {0};
int w[2], c;
struct node{
int water[2];
int step;
string s;
int pre;
int index;
node(){
s = "";
step = 0;
pre = -1;
index = 0;
}
}op[1002];
node BFS(){
queue<node> q;
node start;
op[0].water[0] = 0;
op[0].water[1] = 0;
op[0].step = 0;
op[0].pre = -1;
op[0].index = 0;
q.push(op[0]);
inq[0][0] = 1;
node front, next;
int p = 1;
string s;
while(!q.empty()){
front = q.front();
q.pop();
if(front.water[0] == c || front.water[1] == c){
return front;
}
for(int i = 0; i < 2;i ++){
for(int j = 0; j < 2; j++){
next = front;
if(i == j && next.water[i] != w[i]){ //倒满
next.water[i] = w[i];
char x = i + '0' + 1;
s = "";
s += "FILL(";
s += x;
s += ")";
next.s = s;
}else if(front.water[i] > 0 && front.water[j] < w[j]){ // i 向 j 倒水
char x = i + '0' + 1;
char y = j + '0' + 1;
s = "";
s += "POUR(";
s += x;
s += ",";
s += y;
s += ")";
next.s = s;
int temp = w[j] - front.water[j];
if(front.water[i] >= temp){
next.water[i] -= temp;
next.water[j] = w[j];
} else{
next.water[i] = 0;
next.water[j] += front.water[i];
}
}
if( !inq[next.water[0]][next.water[1]] ){
next.step += 1;
next.index = p;
next.pre = front.index;
op[p++] = next;
inq[next.water[0]][next.water[1]] = 1;
q.push(next);
}
}
}
for(int i = 0; i < 2; i++){ // 倒出
next = front;
next.water[i] = 0;
char x = i + '0' + 1;
s = "";
s += "DROP(";
s += x;
s += ")";
next.s = s;
if( !inq[next.water[0]][next.water[1]] ){
next.step += 1;
next.pre = front.index;
next.index = p;
op[p++] = next;
inq[next.water[0]][next.water[1]] = 1;
q.push(next);
}
}
}
node end;
end.index = -1;
return end;
}
void Printf(node ans){
if(ans.pre == -1){
return ;
}
else{
Printf( op[ans.pre] );
cout << ans.s << endl;
}
}
int main (){
cin >> w[0] >> w[1] >> c;
node ans = BFS();
if(ans.index == -1){
cout << "impossible" << endl;
}else{
cout << ans.step << endl;
Printf(ans);
}
return 0;
}