常规思路:
1.想清楚六种情况,大致想出代码
2.不要忘记剪枝(去除重复状态)
3.对于无解情况加入一个bool判断
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
const int N = 100010;
typedef struct
{
int v1;
int v2;
string op;
} f;
f q[N];
int v1, v2, goal;
int head, tail;
void bfs();
bool p = false;
bool a[105][105] = {false};
int min_length = 0x7fffffff;
string short_str;
int main()
{
cin >> v1 >> v2 >> goal;
bfs();
if (p)
{
cout << min_length << endl;
for (int i = 0; i < short_str.length(); i++)
{
if (short_str[i] == '1')
{
printf("FILL(1)\n");
}
else if (short_str[i] == '2')
{
printf("DROP(1)\n");
}
else if (short_str[i] == '3')
{
printf("POUR(1,2)\n");
}
else if (short_str[i] == '4')
{
printf("FILL(2)\n");
}
else if (short_str[i] == '5')
{
printf("DROP(2)\n");
}
else if (short_str[i] == '6')
{
printf("POUR(2,1)\n");
}
}
}
else
printf("impossible");
system("pause");
return 0;
}
void bfs()
{
f init = {0, 0, ""};
head = tail = 0;
f nwq, cq;
q[head] = init;
while (head <= tail)
{
cq = q[head++];
for (int i = 1; i <= 6; i++)
{
nwq = cq;
if (i == 1)
{
nwq.v1 = v1;
nwq.op += "1";
}
else if (i == 2)
{
nwq.v1 = 0;
nwq.op += "2";
}
else if (i == 3)
{
int d = v2 - nwq.v2;
if (d > nwq.v1)
{
nwq.v2 += nwq.v1;
nwq.v1 = 0;
}
else
{
nwq.v2 = v2;
nwq.v1 -= d;
}
nwq.op += "3";
}
else if (i == 4)
{
nwq.v2 = v2;
nwq.op += "4";
}
else if (i == 5)
{
nwq.v2 = 0;
nwq.op += "5";
}
else if (i == 6)
{
int d = v1 - nwq.v1;
if (d > nwq.v2)
{
nwq.v1 += nwq.v2;
nwq.v2 = 0;
}
else
{
nwq.v1 = v1;
nwq.v2 -= d;
}
nwq.op += "6";
}
if (a[nwq.v1][nwq.v2])
continue;
else
{
a[nwq.v1][nwq.v2] = true;
if (nwq.v1 == goal || nwq.v2 == goal)
{
if (nwq.op.length() < min_length)
{
min_length = nwq.op.length();
short_str = nwq.op;
p = true;
}
}
q[++tail] = nwq;
}
}
}
return;
}