本文共 3941 字,大约阅读时间需要 13 分钟。
为了解决这个问题,我们需要找到一种最短的操作序列,使得其中一个容器中恰好有C升的水。我们可以通过广度优先搜索(BFS)来探索所有可能的状态转换,并找到最短路径。
#include#include #include #include using namespace std;int main() { int a, b, c; scanf("%d%d%d", &a, &b, &c); int MAXN = 100; bool visited[MAXN][MAXN]; queue q; struct node { int curr_a, curr_b; int steps; string path; node(int a, int b, int steps, string path) : curr_a(a), curr_b(b), steps(steps), path(path) {} }; node start_node(0, 0, 0, ""); visited[start_node.curr_a][start_node.curr_b] = true; q.push(start_node); string ops[] = {"", "FILL(1)", "FILL(2)", "DROP(1)", "DROP(2)", "POUR(1,2)", "POUR(2,1)"}; while (!q.empty()) { auto current = q.front(); q.pop(); if (current.curr_a == c || current.curr_b == c) { cout << current.steps << endl; for (int i = 0; i < current.path.size(); ++i) { cout << ops[current.path[i] - '0'] << endl; } return true; } // Generate all possible moves if (current.path.length() >= 7) continue; // 避免无限循环 // FILL(1) if (current.curr_a < a && !visited[current.curr_a + a][current.curr_b]) { node next = node(current.curr_a + a, current.curr_b, current.steps + 1, current.path + "1"); if (next.curr_a <= MAXN && next.curr_b <= MAXN) { if (!visited[next.curr_a][next.curr_b]) { visited[next.curr_a][next.curr_b] = true; q.push(next); } } } // FILL(2) if (current.curr_b < b && !visited[current.curr_a][current.curr_b + b]) { node next = node(current.curr_a, current.curr_b + b, current.steps + 1, current.path + "2"); if (!visited[next.curr_a][next.curr_b]) { visited[next.curr_a][next.curr_b] = true; q.push(next); } } // DROP(1) if (current.curr_a > 0 && !visited[0][current.curr_b]) { node next = node(0, current(curr_b_b), current.steps + 1, current.path + "3"); if (!visited[next.curr_a][next.curr_b]) { visited[next.curr_a][next.curr_b] = true; q.push(next); } } // DROP(2) if (current.curr_b > 0 && !visited[current.curr_a][0]) { node next = node(current(curr_a, 0, current.steps + 1, current.path + "4"); if (!visited[next.curr_a][next.curr_b]) { visited[next.curr_a][next.curr_b] = true; q.push(next); } } // POUR(1,2) int pour_from = current(curr_a, curr_b); if (pour_from.b < b) { int水量 = min(pour_from.a, b - pour_from.b); if (水量 > 0) { node next = node(current(curr_a - 水量, curr_b + 水量, current.steps + 1, current.path + "5"); if (!visited[next.a][next.b]) { visited[next.a][next.b] = true; q.push(next); } } } // POUR(2,1) if (pour_from.a < a) { int水量 = min(pour_from.b, a - pour_from.a); if (水量 > 0) { node next = node(current(a + 水量, b - 水量), steps + 1, path + "6"); if (!visited[next.a][next.b]) { visited[next.a][next.b] = true; q.push(next); } } } } cout << "impossible" << endl; return false;}
visited
来记录状态是否已经被访问过。使用队列进行BFS,存储当前状态、步骤数和路径。通过这种方法,我们可以找到最短的操作序列,或者判断目标状态不可达。
转载地址:http://xlhzk.baihongyu.com/