题目链接:HDU 1495
题意:给一瓶s升的可乐,和两个容量为n,m的杯子(满足n+m==s),问有可能将这杯可乐均分吗?若可能,最少需要多少次倒可乐的操作?
分析:
BFS搜索。每次有6中选择,注意下操作的合法性即可。
CODE:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <cmath>
#include <cctype>
using namespace std;
const int maxn = 105;
int vis[maxn][maxn];//vis[i][j]=1:小杯i升大杯j升已经访问过
int n, m, s, ans ,t;
struct Node {
int a, b, c;//a,b,c分别是小杯、大杯、瓶子中的余量
int step;//达到当前状态的步数
}cur, nextnode;
int bfs()
{
memset(vis, 0, sizeof(vis));
queue<Node> q;
cur.a = 0, cur.b = 0, cur.c = s, cur.step = 0;
vis[0][0] = 1;
q.push(cur);
while (!q.empty())
{
cur = q.front();
q.pop();
for (int i = 0; i < 6; i++)//每次有6种倒法
{
if (i == 0)//s->n
{
if (cur.c == 0 || cur.a == n) continue;
t = cur.c + cur.a;
nextnode.c = t > n ? (t - n) : 0;
nextnode.a = t > n ? n : t;
nextnode.b = cur.b;
}
else if (i == 1)//s->m
{
if (cur.c == 0 || cur.b == m ) continue;
t = cur.c + cur.b;
nextnode.c = t > m ? (t - m) : 0;
nextnode.b = t > m ? m : t;
nextnode.a = cur.a;
}
else if (i == 2)//n->s
{
if (cur.a == 0 || cur.c == s) continue;
nextnode.c = cur.c + cur.a;
nextnode.a = 0;
nextnode.b = cur.b;
}
else if (i == 3)//n->m
{
if (cur.a == 0 || cur.b == m) continue;
t= cur.a + cur.b;
nextnode.b = t < m ? t : m;
nextnode.a = t < m ? 0 : (t - m);
nextnode.c = cur.c;
}
else if(i==4)//m->s
{
if (cur.b == 0 || cur.c == s) continue;
nextnode.b = 0;
nextnode.c = cur.b + cur.c;
nextnode.a = cur.a;
}
else if(i==5)//m->n
{
if (cur.b == 0 || cur.a == n) continue;
t = cur.a + cur.b;
nextnode.a = t < n ? t : n;
nextnode.b = t < n ? 0 : (t - n);
nextnode.c = cur.c;
}
nextnode.step = cur.step + 1;
if (nextnode.b == s / 2) return nextnode.step;
if (!vis[nextnode.a][nextnode.b])
{
q.push(nextnode);
vis[nextnode.a][nextnode.b] = 1;
}
}
}
return -1;
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
while (cin >> s >> n >> m)
{
if (s == 0) break;
if (s % 2) {//奇数时由于杯子量度都是整数,所以永远不可能被均分
cout << "NO" << endl;
continue;
}
if (n * 2 == s || m * 2 == s) {
cout << 1 << endl;
continue;
}
if (n > m) swap(n, m);//规定了n<m<s,那么退出条件就是:成功m*2==s,失败:队列为空
ans = bfs();
if (ans == -1) cout << "NO"<< endl;
else cout << ans+1 << endl;//别忘了+1!
}
return 0;
}