【三个水杯 NYOJ  21  广搜】

唉...这道题写了好久啊!
简单的宽度优先搜索,三个水杯之间的相互倒水如下图6种情况:


对于每一次倒水都会引起三个水杯水量状态的改变,这样就可以得到如下的一个解空间树:


按照上图中得到解空间树的方法,代码如下:

#include <cstdio>
#include <memory.h>
#include <queue>

using namespace std;

#define EMPTY    0

struct data_type
{
	int state[3];
	int step;
};

int cupCapacity[3], targetState[3];

bool visited[100][100][100];

bool AchieveTargetState(data_type current)
{
	for (int i = 0; i < 3; i++)
	{
		if (current.state[i] != targetState[i])
		{
			return false;
		}
	}
	return true;
}

void PourWater(int destination, int source, data_type &cup)
{
	int waterYield = cupCapacity[destination] - cup.state[destination];
	if (cup.state[source] >= waterYield)
	{
		cup.state[destination] += waterYield;
		cup.state[source] -= waterYield;
	}
	else
	{
		cup.state[destination] += cup.state[source];
		cup.state[source] = 0;
	}
}

int BFS(void)
{
	int i, j, k;
	data_type initial;
	queue<data_type> toExpandState;

	memset(visited, false, sizeof(visited));
	initial.state[0] = cupCapacity[0];
	initial.state[1] = initial.state[2] = 0;
	initial.step = 0;
	toExpandState.push(initial);
	visited[initial.state[0]][0][0] = true;

	while (!toExpandState.empty())
	{
		data_type node = toExpandState.front();
		toExpandState.pop();
		if (AchieveTargetState(node))
		{
			return node.step;
		}
		for (i = 0; i < 3; i++)
		{
			for (j = 1; j < 3; j++)
			{
				k = (i+j)%3;
				if (node.state[i] != EMPTY && node.state[k] < cupCapacity[k])
				{
					data_type newNode = node;
					PourWater(k, i, newNode);
					newNode.step = node.step + 1;
					if (!visited[newNode.state[0]][newNode.state[1]][newNode.state[2]])
					{
						visited[newNode.state[0]][newNode.state[1]][newNode.state[2]] = true;
						toExpandState.push(newNode);
					}
				}
			}
		}
	}
	return -1;
}

int main(void)
{
	int testNum;
	scanf("%d", &testNum);
	while (testNum -- != 0)
	{
		scanf("%d%d%d", &cupCapacity[0], &cupCapacity[1], &cupCapacity[2]);
		scanf("%d%d%d", &targetState[0], &targetState[1], &targetState[2]);
		printf("%d\n", BFS());
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

paidream

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值