您的位置:首页 > 其它

NYOJ 21--三个水杯【BFS】

2015-11-22 17:44 344 查看


三个水杯

时间限制: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


解析: 水题搜索,和杭电1495基本一样,解析点我

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int V1, V2, V3;
int E1, E2, E3;

int vis[100][100][100];

struct node {
int v1, v2, v3, step;
};

void BFS(){
memset(vis, 0, sizeof(vis));
node st, ed;
queue<node>q;
st.v1 = V1, st.v2 = 0, st.v3 = 0;
st.step = 0;
vis[V1][V2][V3] = 1;
q.push(st);
while(!q.empty()){
st = q.front();
q.pop();
if(st.v1 == E1 && st.v2 == E2 && st.v3 == E3){
printf("%d\n", st.step);
return;
}
if(st.v1){
// v1 -> v2
if(st.v1 > V2 - st.v2){ //可以倒满
ed.v1 = st.v1 - (V2 - st.v2);
ed.v2 = V2;
ed.v3 = st.v3;
ed.step = st.step + 1;
}
else{
ed.v1 = 0;
ed.v2 = st.v2 + st.v1;
ed.v3 = st.v3;
ed.step = st.step + 1;
}
if(!vis[ed.v1][ed.v2][ed.v3])
vis[ed.v1][ed.v2][ed.v3] = 1, q.push(ed);
// v1 -> v3
if(st.v1 > V3 - st.v3){
ed.v1 = st.v1 - (V3 - st.v3);
ed.v2 = st.v2;
ed.v3 = V3;
ed.step = st.step + 1;
}
else{
ed.v1 = 0;
ed.v2 = st.v2;
ed.v3 = st.v3 + st.v1;
ed.step = st.step + 1;
}
if(!vis[ed.v1][ed.v2][ed.v3])
vis[ed.v1][ed.v2][ed.v3] = 1, q.push(ed);
}
if(st.v2){
// v2 -> v3
if(st.v2 > V3 - st.v3){ //可以倒满
ed.v1 = st.v1;
ed.v2 = st.v2 - (V3 - st.v3);
ed.v3 = V3;
ed.step = st.step + 1;
}
else{
ed.v1 = st.v1;
ed.v2 = 0;
ed.v3 = st.v3 + st.v2;
ed.step = st.step + 1;
}
if(!vis[ed.v1][ed.v2][ed.v3])
vis[ed.v1][ed.v2][ed.v3] = 1, q.push(ed);
// v2 -> v1
if(st.v2 > V1 - st.v1){
ed.v1 = V1;
ed.v2 = st.v2 - (V1 - st.v1);
ed.v3 = st.v3;
ed.step = st.step + 1;
}
else{
ed.v1 = st.v1 + st.v2;
ed.v2 = 0;
ed.v3 = st.v3;
ed.step = st.step + 1;
}
if(!vis[ed.v1][ed.v2][ed.v3])
vis[ed.v1][ed.v2][ed.v3] = 1, q.push(ed);
}
if(st.v3){
// v3 -> v1
if(st.v3 > V1 - st.v1){ //可以倒满
ed.v1 = V1;
ed.v2 = st.v2;
ed.v3 = st.v3 - (V1 - st.v1);
ed.step = st.step + 1;
}
else{
ed.v1 = st.v1 + st.v3;
ed.v2 = st.v2;
ed.v3 = 0;
ed.step = st.step + 1;
}
if(!vis[ed.v1][ed.v2][ed.v3])
vis[ed.v1][ed.v2][ed.v3] = 1, q.push(ed);
// v3 -> v2
if(st.v3 > V2 - st.v2){
ed.v1 = st.v1;
ed.v2 = V2;
ed.v3 = st.v3 - (V2 - st.v2);
ed.step = st.step + 1;
}
else{
ed.v1 = st.v1;
ed.v2 = st.v2 + st.v3;
ed.v3 = 0;
ed.step = st.step + 1;
}
if(!vis[ed.v1][ed.v2][ed.v3])
vis[ed.v1][ed.v2][ed.v3] = 1, q.push(ed);
}
}
printf("-1\n");
return;
}

int main (){
int T;
scanf("%d", &T);
while(T--){
scanf("%d%d%d", &V1, &V2, &V3);
scanf("%d%d%d", &E1, &E2, &E3);
BFS();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: