-
描述
-
给出三个水杯,大小不一,并且只有最大的水杯的水是装满的,其余两个为空杯子。三个水杯之间相互倒水,并且水杯没有标识,只能根据给出的水杯体积来计算。现在要求你写出一个程序,使其输出使初始状态到达目标状态的最少次数。
-
输入
-
第一行一个整数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
-
第一行一个整数N(0<N<50)表示N组测试数据
数据给的不是很大,很明显的暴力搜索,但是设计函数的时候想破了脑子,看了一下前辈的代码,想起来之前学过的用队列求解BFS。
其中比较难考虑的就是找倒水能找到的最小值,不过这最小值其实就是需要倒满的杯子的其中一个还需要多少,或者目前已有状态中最小的值。
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
struct state
{
int cur[3];
int v[3];
int step;
};
state start, endness;
queue<state> q;
int vis[1000000 + 10];
int Hash(state s)
{
return (s.cur[0]*10000 + s.cur[1]*100 + s.cur[2]);
}
int Final(state s1, state s2)
{
return (s1.cur[0] == s2.cur[0] && s1.cur[1] == s2.cur[1] && s1.cur[2] == s2.cur[2]);
}
int main()
{
int T;
int flag;
int minn;
scanf("%d", &T);
while (T--)
{
scanf("%d%d%d", &start.v[0], &start.v[1], &start.v[2]);
start.cur[0] = start.v[0];
start.cur[1] = start.cur[2];
start.step = 0;
scanf("%d%d%d", &endness.cur[0], &endness.cur[1], &endness.cur[2]);
flag = 0;
memset(vis, 0, sizeof(vis));
q.push(start);
vis[Hash(start)] = 1;
while (!q.empty())
{
state now = q.front();
q.pop();
if (Final(now, endness) == 1)
{
printf("%d\n", now.step);
flag = 1;
break;
}
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
if (i != j)
{
///下面是找到那个最小值
minn = now.v[j] - now.cur[j];
if (now.cur[i] < minn)
minn = now.cur[i];
state candidate = now;
candidate.cur[i] -= minn;
candidate.cur[j] += minn;
candidate.step = now.step + 1;
if (vis[Hash(candidate)] == 0)
{
vis[Hash(candidate)] = 1;
q.push(candidate);
}
}
}
}
}
if (flag == 0)
printf("-1\n");
while (!q.empty())
q.pop();
}
return 0;
}