kuangbin带你飞——专题一 简单搜索(13)
题目来源:HDU 1495 非常可乐
HDU网址改动,VJ无法正常提交,附HDU新网址
题解
类似Pots的题型,但是更简单。
给一瓶容量为 S 的可乐,用两个容量分别为 N 和 M 的杯子以及可乐瓶本身将可乐平分。
BFS记忆化搜索
,遍历六个方向分别为 1 -> 2 , 1 -> 3 , 2 -> 1 , 2 -> 3 , 3 -> 1 , 3 -> 2。
AC代码
#include <bits/stdc++.h>
using namespace std;
int s, n, m;
// 存储六个方向
typedef pair<int, int> Pair;
Pair p[6] = {{1, 2}, {1, 3}, {2, 1}, {2, 3}, {3, 1}, {3, 2}};
// 存储操作
struct status
{
int ta, tb, tc;
int step;
};
status sta[10000];
int bfs(int c, int a, int b)
{
int cnt = 1;
sta[0] = {0, 0, c, 0};
// 遍历数组
for (int i = 0;; ++i)
{
// 超出边界 break
if (i >= cnt)
break;
// 遍历六个方向
for (int j = 0; j < 6; ++j)
{
status tmp = sta[i];
++tmp.step;
if (j == 0)
{
if (tmp.ta == 0 || tmp.tb == m)
continue;
int pour = min(tmp.ta, m - tmp.tb);
tmp.ta -= pour, tmp.tb += pour;
}
else if (j == 1)
{
if (tmp.ta == 0 || tmp.tc == s)
continue;
int pour = min(tmp.ta, s - tmp.tc);
tmp.ta -= pour, tmp.tc += pour;
}
else if (j == 2)
{
if (tmp.tb == 0 || tmp.ta == n)
continue;
int pour = min(tmp.tb, n - tmp.ta);
tmp.tb -= pour, tmp.ta += pour;
}
else if (j == 3)
{
if (tmp.tb == 0 || tmp.tc == s)
continue;
int pour = min(tmp.tb, s - tmp.tc);
tmp.tb -= pour, tmp.tc += pour;
}
else if (j == 4)
{
if (tmp.tc == 0 || tmp.ta == n)
continue;
int pour = min(tmp.tc, n - tmp.ta);
tmp.tc -= pour, tmp.ta += pour;
}
else
{
if (tmp.tc == 0 || tmp.tb == m)
continue;
int pour = min(tmp.tc, m - tmp.tb);
tmp.tc -= pour, tmp.tb += pour;
}
// 到达目标 return
if ((tmp.ta == tmp.tb && tmp.tc == 0) || (tmp.ta == tmp.tc && tmp.tb == 0) || (tmp.tb == tmp.tc && tmp.ta == 0))
return tmp.step;
// 判断是否存储
bool flag = 1;
for (int k = 0; k < cnt; ++k)
{
if (tmp.ta == sta[k].ta && tmp.tb == sta[k].tb && tmp.tc == sta[k].tc)
flag = 0;
}
if (flag)
{
sta[cnt++] = tmp;
}
}
}
return -1;
}
int main()
{
while (~scanf("%d%d%d", &s, &n, &m) && s)
{
if (s % 2 != 0)
printf("NO\n");
else
{
int ans = bfs(s, n, m);
if (ans == -1)
printf("NO\n");
else
printf("%d\n", ans);
}
}
return 0;
}