#include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <queue>
using namespace std;
struct node
{
int x[3];//记录倒水过程中倒水的状态,利用相应的中间状态进行记录
int step;
};
int vis[205][205];//注意vis数组用于
int s, n, m;
int cup_left[3] = { 0 };//记录三个杯子中每个杯子的剩余状态
int bfs()
{
queue<node>q;
node a;
a.x[0] = cup_left[0];//最大杯子初始状态
a.x[1] = 0;
a.x[2] = 0;
a.step = 0;
q.push(a);
vis[0][0] = 1;
node now, next;
while (!q.empty())
{
now = q.front(); q.pop();
if (now.x[0] == now.x[1] && now.x[2] == 0)//注意最终可能的状态只能是最大的杯子与最小的杯子平分
{
return now.step;
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
int left;//记录可能的倒水的量,只能是一个杯子将水倒空,另外一个杯子把水倒满
if (i == j)
continue;
left = min(now.x[i], cup_left[j] - now.x[j]);//利用i,j控制倒水的杯子与接水的杯子
for (int k = 0; k < 3; k++)
{
next.x[k] = now.x[k];//记录倒水之前的状态,方便计算
}//三种杯子的状态均要记录
next.x[i] = now.x[i] - left;
next.x[j] = now.x[j] + left;
if (!vis[next.x[1]][next.x[2]])//以中间两个杯子的状态进行判断是否进行过访问
{
next.step = now.step + 1;
q.push(next);
vis[next.x[1]][next.x[2]] = 1;
}
}
}
}
return -1;
}
int main()
{
while (scanf("%d %d %d", &s, &n, &m) == 3)
{
if (s == 0 && n == 0 && m == 0)
break;
memset(cup_left, 0, sizeof(cup_left));
memset(vis, 0, sizeof(vis));
if (s % 2 != 0)//奇数情况直接剪枝进行判断
{
printf("NO\n");
continue;
}
cup_left[0] = s;//记录最大杯子
cup_left[1] = max(n, m);//记录中间杯子的容量,注意固定相应的表示方法
cup_left[2] = min(n, m);//最小杯子
int result = bfs();
if (result == -1)
{
printf("NO\n");
}
else
{
printf("%d\n", result);
}
}
getchar();
getchar();
return 0;
}
1、第二次做这道题,感觉理解有加深了一点,关键要注意理解三个杯子进行倒水时对于状态的理解,最后的平分状态只能是最大的杯子与中等的杯子平分,并且我们还可以在输入时进行剪枝判断,如果输入的可乐的容量为奇数,直接可以判断不能平分
2、其他则是bfs的模块化处理,利用队列,其中关键在于6种倒水状态的控制,三个杯子有六种不同的倒水状态,则利用i控制倒水的杯子,j控制接受水的杯子
3、重点!!!两个杯子倒水时,只能是两种情况,第一种情况时倒水的杯子将水倒满了,而接受水的杯子还没有满,第二种情况是倒水的杯子倒不完,但接受水的杯子已经满了,此处需要一个状态判断,实际倒的水应该是两种情况的最小值,其余的直接利用bfs搜索就可以了
4、此题有一处细节,分大,中,小三种杯子,并且固定三种杯子的表示方式