poj3414 Pots(BFS)
2017-11-21 20:39
288 查看
题目链接
http://poj.org/problem?id=3414
题意
有两个杯子,容量分别为A升,B升,可以向杯子里倒满水,将杯子里的水倒空,将一个杯子里的水倒到另一个杯子里,求怎样倒才能使其中的一个杯子里的水恰为C升,输出最少步数和操作;如果不能倒到C升,输出“impossible”。
思路
这题与poj1606基本相同,在poj1606的基础上添加了输出最少步数,修改了操作的表示,以及不可能达到目标时输出impossible。将poj1606的代码略作修改即可。
代码
#include <iostream> #include <cstdio> #include <cstring> #include <queue> #include <stack> using namespace std; struct Node { int a, b; int steps; int flag; Node* pre; }; const int N = 1010; int ca, cb, n; int visit ; stack<int> s; void print() { while (!s.empty()) { switch (s.top()) { case 0: cout << "FILL(1)" << endl; break; case 1: cout << "FILL(2)" << endl; break; case 2: cout << "DROP(1)" << endl; break; case 3: cout << "DROP(2)" << endl; break; case 4: cout << "POUR(1,2)" << endl; break; case 5: cout << "POUR(2,1)" << endl; break; } s.pop(); } } void bfs(int a, int b) { Node state ; int cnt = -1; memset(visit, 0, sizeof(visit)); Node node; node.a = node.b = 0; node.steps = 0; node.pre = NULL; queue<Node> q; q.push(node); visit[node.a][node.b] = 1; while (!q.empty()) { Node node = q.front(); q.pop(); state[++cnt] = node; Node next = node; for (int i = 0; i < 6; i++) { next = node; int amount; switch (i) { case 0: //FILL(1) next.a = ca; next.flag = 0; break; case 1: //FILL(2) next.b = cb; next.flag = 1; break; case 2: // DROP(1) next.a = 0; next.flag = 2; break; case 3: //DROP(2) next.b = 0; next.flag = 3; break; case 4: //POUR(1,2) amount = cb - node.b; if (node.a > amount) { next.a -= amount; next.b = cb; } else { next.a = 0; next.b = node.a + node.b; } next.flag = 4; break; case 5: //POUR(2,1) amount = ca - node.a; if (node.b > amount) { next.a = ca; next.b -= amount; } else { next.a = node.a + node.b; next.b = 0; } next.flag = 5; break; } if (!visit[next.a][next.b]) { visit[next.a][next.b] = 1; next.pre = &state[cnt]; next.steps = node.steps + 1; if (next.a == n || next.b == n) { cout << next.steps << endl; while (next.pre) { s.push(next.flag); next = *next.pre; } print(); return; } q.push(next); } } } cout << "impossible" << endl; } int main() { cin >> ca >> cb >> n; bfs(0, 0); return 0; }
相似题目
相关文章推荐
- POJ3414 Pots BFS搜索 TWT TokyoOlympic 4combo-2
- poj3414--Pots(bfs,记录路径)
- 【POJ3414】Pots(BFS)
- POJ3414 Pots【倒水问题+BFS】
- POJ3414—Pots(bfs加回溯)
- poj3414--Pots(bfs,记录路径)
- POJ3414 Pots(BFS)
- poj3414 Pots(BFS)
- poj 3414 pots -- 最爱的 BFS (记录路径)
- POJ-3414(Pots)——BFS
- POJ 3414 Pots【bfs模拟倒水问题】
- poj Pots(BFS)(路径记录)(模拟)
- poj3414_pots
- POJ 3414 Pots (BFS)
- 【宽度优先搜索】poj3414 Pots
- poj3414(用bfs模拟并回溯)
- POJ 3414--Pots(BFS+回溯路径)
- BFS-POJ-3414-Pots
- POJ 3414 Pots【bfs模拟倒水问题】
- poj Pots(BFS)(路径记录)(模拟)