NYOJ-21-三个水杯

三个水杯

时间限制: 1000 ms  |  内存限制: 65535 KB
难度: 4
描述
给出三个水杯,大小不一,并且只有最大的水杯的水是装满的,其余两个为空杯子。三个水杯之间相互倒水,并且水杯没有标识,只能根据给出的水杯体积来计算。现在要求你写出一个程序,使其输出使初始状态到达目标状态的最少次数。
输入
第一行一个整数N(0<N<50)表示N组测试数据
接下来每组测试数据有两行,第一行给出三个整数V1 V2 V3 (V1>V2>V3 V1<100 V3>0)表示三个水杯的体积。
第二行给出三个整数E1 E2 E3 (体积小于等于相应水杯体积)表示我们需要的最终状态
输出
每行输出相应测试数据最少的倒水次数。如果达不到目标状态输出-1
样例输入
2
6 3 1
4 1 1
9 3 2
7 1 1
样例输出
3
-1
 
    
我觉得画图更好找到规律,如图:根据图很明确看出用广搜来做并能找出其中的规律。
 
    
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int MAXV = 100;
int startCup[3], endCup[3];
bool visited[MAXV][MAXV][MAXV];

struct CupSate
{
	int cup[3];
	int step;
};
queue<CupSate> q;

void pourWater(int from, int to, CupSate current)
{
    CupSate temp = current;
    int t = startCup[to] - temp.cup[to];
    if (temp.cup[from] >= t)
    {
        temp.cup[to] += t;
        temp.cup[from] -= t;
    }
    else
    {
        temp.cup[to] += temp.cup[from];
        temp.cup[from] = 0;
    }
    if (visited[temp.cup[0]][temp.cup[1]][temp.cup[2]] == false)
    {
        visited[temp.cup[0]][temp.cup[1]][temp.cup[2]] = true;
        temp.step++;
        q.push(temp);
    }
}
int BSF()
{
	while (!q.empty())
		q.pop();
	CupSate init;
	init.cup[0] = startCup[0];
	init.cup[1] = init.cup[2] = init.step = 0;
	q.push(init);
	while (!q.empty())
	{
		CupSate current;
		current = q.front();
		//printf("%d %d %d %d\n", current.cup[0], current.cup[1],current.cup[2],current.step);
		q.pop();
		if (current.cup[0] == endCup[0] && current.cup[1] == endCup[1] && current.cup[2] == endCup[2])
			return current.step;
		if (current.cup[0] > 0 && startCup[1] > current.cup[1])
		{
			pourWater(0, 1, current);
		}
		if (current.cup[0] > 0 && startCup[2] > current.cup[2])
		{
			pourWater(0, 2, current);
		}
		if (current.cup[1] > 0 && startCup[0] > current.cup[0])
		{
			pourWater(1, 0, current);
		}
		if (current.cup[1] > 0 && startCup[2] > current.cup[2])
		{
			pourWater(1, 2, current);
		}
		if (current.cup[2] > 0 && startCup[0] > current.cup[0])
		{
			pourWater(2, 0, current);
		}
		if (current.cup[2] > 0 && startCup[1] > current.cup[1])
		{
			pourWater(2, 1, current);
		}
	}
	return -1;
}
int main()
{
	int n;
	scanf("%d", &n);
	while (n--)
	{
        scanf("%d %d %d", &startCup[0], &startCup[1], &startCup[2]);
        scanf("%d %d %d", &endCup[0], &endCup[1], &endCup[2]);
        memset(visited, false, sizeof(visited));
        visited[startCup[0]][0][0] = true;
		printf("%d\n", BSF());
	}
	return 0;
}



 
   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值