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 <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; }