3个水杯

三个水杯

时间限制: 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<stdio.h>
#include<iostream>
#include<queue>
#include<string.h>

using namespace std;

typedef int array[10];
typedef struct cup {
	array a;
	int step;
}cup;
array  end, start;
int hash[100][100][100];
cup curr;
queue<cup> q;

void bfs()
{
	int i, j, k;
	cup next;
	while(!q.empty()){
		curr = q.front();
		q.pop();
		if(curr.a[0] == end[0] && curr.a[1] == end[1] && curr.a[2] == end[2] ){
			printf("%d\n",curr.step);
			return;
		}
	
		for(i = 0; i < 3; i++){
			for(j = 0; j < 3; j++){
				if(j != i){
					next.a[0] = curr.a[0];
					next.a[1] = curr.a[1];
					next.a[2] = curr.a[2];
					if(curr.a[i] &&  curr.a[i] > start[j] - curr.a[j]){
						next.a[i] = curr.a[i] - (start[j] - curr.a[j]);
						next.a[j] = start[j];
					}
					else if(curr.a[i] && curr.a[i] <= start[j] - curr.a[j]) {
						next.a[i] = 0;
						next.a[j] = curr.a[j] +  curr.a[i];
					}
					else
						continue;
				/*	if(next.a[0] == end[0] && next.a[1] == end[1] && next.a[2] == end[2] ){
						printf("%d\n", curr.step + 1);	
						return ;
					}*/
					if(hash[next.a[0]][next.a[1]][next.a[2]] == 0){
						hash[next.a[0]][next.a[1]][next.a[2]] = 1;
						next.step = curr.step + 1;	
						q.push(next);	
					}
				}
			}
		}
	}
	printf("-1\n");

}
int main()
{
	int n;
	int i;
	scanf("%d", &n);
	while(n--){
		memset(hash, 0, sizeof(hash));
		while(!q.empty())
			q.pop();

		scanf("%d%d%d", &start[0],&start[1],&start[2]);
		scanf("%d%d%d",&end[0],&end[1],&end[2]);
			hash[start[0]][0][0] = 1; 
			curr.a[0] = start[0];
			curr.a[1] = 0;
			curr.a[2] = 0;
		curr.step = 0;
		q.push(curr);
		bfs();
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值