1. 程式人生 > >nyoj 21 三個水杯

nyoj 21 三個水杯

light spa ems 相互 site define front pan 測試

三個水杯

時間限制: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 <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;
}        

  

nyoj 21 三個水杯