HDU-1495 非常可乐

非常可乐

Problem Description

大家一定觉的运动以后喝可乐是一件很惬意的事情,但是seeyou却不这么认为。因为每次当seeyou买了可乐以后,阿牛就要求和seeyou一起分享这一瓶可乐,而且一定要喝的和seeyou一样多。但seeyou的手中只有两个杯子,它们的容量分别是N 毫升和M 毫升 可乐的体积为S (S<101)毫升 (正好装满一瓶) ,它们三个之间可以相互倒可乐 (都是没有刻度的,且 S==N+M,101>S>0,N>0,M>0) 。聪明的ACMER你们说他们能平分吗?如果能请输出倒可乐的最少的次数,如果不能输出"NO"。

 

 

Input

三个整数 : S 可乐的体积 , N 和 M是两个杯子的容量,以"0 0 0"结束。

 

Output

如果能平分的话请输出最少要倒的次数,否则输出"NO"。

 

Sample Input

7 4 3

4 1 3

0 0 0

 

 

Sample Output

NO

3

 

思路:有3个容器,把容器中的可乐相互倾倒。6种可能,s→n,s→m;n→s,n→m;m→s,m→n,模拟6种情况(也可以用其他方法模拟,我写的是最容易想到的)。用数组标记状态,避免无用操作。倒可乐时只用判断是否能倒满即可,倒完后三个容器的情况如果符合实际,就加入队列,进行广搜。代码如下:

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <math.h>
#include <queue>
#include <vector>
#include <string.h>
#include <sstream>
#include <set>
#include <map>
#include <stack>
#include <utility>
#define LL long long
using namespace std;
const int maxn = 105;
int s, n, m;
int vis[maxn][maxn];
struct node {
	int ss, nn, mm;
	node(int x, int y, int z) { ss = x; nn = y; mm = z; }
};
queue<node>q;
int bfs(node a, node b)//用两个结构体,易于操作
{
	q.push(a);
	vis[0][0] = 1;//初始起点
	while (!q.empty())
	{
		b = q.front();//这里先不要释放队首元素,在循环结束时释放,因为要给a赋值
		if (b.ss == s / 2) {
			return vis[b.nn][b.mm]-1;//起适步数为1
		}
		for (int i = 0; i < 6; i++)//模拟6种情况。其实倒可乐时只考虑能否倒满,是否合理在后面判断
		{
			a = q.front();//使a与b等
			if (i == 0) {
				if (b.ss > n - b.nn) {
					a.ss = b.ss - n + b.nn;
					a.nn = n;
				}
				else {
					a.nn += b.ss;
					a.ss = 0;
				}
			}
			if (i == 1) {
				if (b.ss > m - b.mm) {
					a.ss = b.ss - m + b.mm;
					a.mm = m;
				}
				else {
					a.mm += b.ss;
					a.ss = 0;
				}
			}
			if (i == 2) {
				if (b.nn > s - b.ss) {
					a.nn = b.nn - s + b.ss;
					a.ss = s;
				}
				else {
					a.ss += b.nn;
					a.nn = 0;
				}
			}
			if (i == 3) {
				if (b.nn > m - b.mm) {
					a.nn = b.nn - m + b.mm;
					a.mm = m;
				}
				else {
					a.mm += b.nn;
					a.nn = 0;
				}
			}
			if (i == 4)
			{
				if (b.mm > s - b.ss) {
					a.mm = b.mm - s + b.ss;
					a.ss = s;
				}
				else {
					a.ss += b.mm;
					a.mm = 0;
				}
			}
			if (i == 5) {
				if (b.mm > n - b.nn) {
					a.mm = b.mm - n + b.nn;
					a.nn = n;
				}
				else {
					a.nn += b.mm;
					a.mm = 0;
				}
			}
            //判断倒完后容器内可乐的多少是否符合实际以及是不是已经倒出过这个结果
			if (!vis[a.nn][a.mm] && a.nn >= 0 && a.nn <= n&&a.mm >= 0 && a.mm <= m&&a.ss >= 0 && a.ss <=s)//注意是<= 可以刚好把容器倒满的
			{
				vis[a.nn][a.mm] = vis[b.nn][b.mm] + 1;
				q.push(a);
			}
		}
		q.pop();//在这里释放队首元素
	}
	return 0;
}
int main()
{
	while (scanf("%d %d %d", &s, &n, &m)==3)
	{
		if (s == 0 && n == 0 && m == 0)break;
		if (s % 2 != 0) {//总可乐数为奇数时一定不能倒出一半,因为可乐数量是整型数据
			printf("NO\n");
			continue;
		}
		while (!q.empty())q.pop();//清空队列
		memset(vis, 0, sizeof(vis));//初始化状态数组
		int f = bfs(node(s, 0, 0), node(s, 0, 0));
		if (f == 0)printf("NO\n");
		else printf("%d\n", f);
	}
	return 0;
}

 

posted @ 2019-07-27 16:02  whocarethat  阅读(111)  评论(0编辑  收藏  举报