题解
使用BFS搜索,每次尝试将某个桶的水倒掉、装满、倒进另一个。
a桶装的水*1000+b桶装的水作为当前状态hash值,利用hash值标记,已经搜索过的状态不再进行入队。
可能操作次数很多,为了性能,存储操作时创建path元素,使用nxt记录路径进行拉链。
除了AB容量为C时,只有在一个桶倒进另一个桶时才可能出现容量为C。
AC代码
#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#define fst first
#define sed second
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const int N = 1e6;
bool vis[N];
char str[3][20] = { "FILL(%d)", "DROP(%d)", "POUR(%d,%d)" }, buf[20];
int V[2], C;
struct path
{
int t, x, y; //类型 值1 值2
int nxt;
path(int a = 0, int b = 0, int c = 0, int d = 0) : t(a), x(b), y(c), nxt(d) {}
}p[N];
int tot;
struct node
{
int v[2], k, t; //k次数 t轨迹
node(int *a, int b, int c)
{
v[0] = a[0], v[1] = a[1], k = b, t = c;
}
};
bool check(int *arr)
{
int v = arr[0] * 1000 + arr[1];
int res = !vis[v];
vis[v] = 1; //标记
return res;
}
void BFS()
{
int f[2] = { 0 }, k, t;
queue<node> q;
q.push(node(f, 0, 0));
vis[0] = 1;
while (!q.empty())
{
k = q.front().k + 1, t = q.front().t;
for (int i = 0; i < 2; ++i)
{
memcpy(f, q.front().v, sizeof(f));
f[i] = V[i]; //填满
if (check(f))
{
p[++tot] = path(0, i, 0, t);
q.push(node(f, k, tot));
}
f[i] = 0; //倒掉
if (check(f))
{
p[++tot] = path(1, i, 0, t);
q.push(node(f, k, tot));
}
memcpy(f, q.front().v, sizeof(f));
int m = min(f[i], V[!i] - f[!i]); //倒进另一个 min(剩余, 另一个空间)
f[i] -= m, f[!i] += m;
if (check(f))
{
p[++tot] = path(2, i, !i, t);
if (f[i] == C || f[!i] == C) //只会再此出现等于C
{
cout << k << endl;
vector<string> vec;
for (int i = tot; i; i = p[i].nxt) //沿着轨迹输出
{
sprintf(buf, str[p[i].t], p[i].x + 1, p[i].y + 1);
vec.push_back(buf);
}
reverse(vec.begin(), vec.end()); //反向
for (int i = 0; i < vec.size(); ++i)
printf("%s\n", vec[i].c_str());
return;
}
q.push(node(f, k, tot));
}
}
q.pop();
}
printf("impossible\n");
}
int main()
{
#ifdef LOCAL
freopen("C:/input.txt", "r", stdin);
#endif
cin >> V[0] >> V[1] >> C;
if (V[0] == C)
printf("1\nFILL(1)\n"), exit(0);
if (V[1] == C)
printf("1\nFILL(2)\n"), exit(0);
BFS();
return 0;
}