您的位置:首页 > 其它

POJ - 3414 bfs [kuangbin带你飞]专题一

2017-02-13 13:32 351 查看
     状态搜索,每种状态下面共有六种选择,将搜索到的状态保存即可。

    d[i][j]表示状态A杯中水i升,B杯中水j升,总状态数量不会超过A杯的容量 * B杯的容量。

AC代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<string>
#include<algorithm>
#include<iostream>
using namespace std;
const int maxn = 100 + 5;

struct node{
int A, B; //当前状态
string op;
node(){
}
node(int a, int b, string op):A(a), B(b), op(op){
}
}pre[maxn][maxn];

int d[maxn][maxn], a, b, c;

void print(int x, int y){
//printf("%d %d\n", x, y);
int px = pre[x][y].A, py = pre[x][y].B;
if(px == -1 && py == -1) return;
print(px, py);
cout << pre[x][y].op << endl;
}

int bfs(){
int cup[] = {a, b};
memset(d, -1, sizeof(d));
d[0][0] = 0;
queue<node>q;
q.push(node(0, 0, ""));
pre[0][0] = node(-1, -1, "");
while(!q.empty()) {
node p = q.front();
q.pop();
if(p.A == c || p.B == c){
printf("%d\n", d[p.A][p.B]);
print(p.A, p.B);
return 1;
}
int w[] = {p.A, p.B};
for(int i = 0; i < 2; ++i)
for(int j = 0; j < 2; ++j) {
if(i == j) continue;
//Fill
w[0] = p.A, w[1] = p.B;
w[i] = cup[i];
if(d[w[0]][w[1]] == -1) {
d[w[0]][w[1]] = d[p.A][p.B] + 1;
string op = "";
if(i == 0) op = "FILL(1)";
else op = "FILL(2)";
q.push(node(w[0], w[1], ""));
pre[w[0]][w[1]] = node(p.A, p.B, op);
}

//Drop
w[0] = p.A, w[1] = p.B;
w[i] = 0;
if(d[w[0]][w[1]] == -1) {
d[w[0]][w[1]] = d[p.A][p.B] + 1;
string op = "";
if(i == 0) op = "DROP(1)";
else op = "DROP(2)";
q.push(node(w[0], w[1], ""));
pre[w[0]][w[1]] = node(p.A, p.B, op);
}

//Pour
w[0] = p.A, w[1] = p.B;
int pour = min(w[i], cup[1 - i] - w[1 - i]);
w[i] -= pour, w[1 -i] += pour;
if(d[w[0]][w[1]] == -1) {
d[w[0]][w[1]] = d[p.A][p.B] + 1;
string op = "";
if(i == 0) op = "POUR(1,2)";
else op = "POUR(2,1)";
q.push(node(w[0], w[1], ""));
pre[w[0]][w[1]] = node(p.A, p.B, op);
}
}
}
return 0;
}

int main(){
while(scanf("%d%d%d", &a, &b, &c) == 3){
if(!bfs()) printf("impossible\n");
}
return 0;
}

如有不当之处欢迎指出!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: