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<map>
#include<set>
#include<queue>
#include<math.h>
#include<vector>
#include<string>
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
#define inf 0x3f3f3f3f
#define ll long long
#define maxn 100100
#define maxm 400105
using namespace std;
struct node{
    int x,y,z,step;
};
node S,T;
int E1,E2,E3;int v1,v2,v3;
bool vis[100][100][100];
int bfs(){
    queue<node>q;
    memset(vis,false,sizeof(vis));
    vis[S.x][S.y][S.z]=true;
    q.push(S);while(!q.empty()){
      T=q.front();q.pop();
      int x=T.x,y=T.y,z=T.z,step=T.step;//cout<<x<<y<<z<<step<<endl;
      if(x==E1&&y==E2&&z==E3) return step;
      if(x>0){
        if(y<v2){T.x=x-min(x,v2-y);T.y=y+min(x,v2-y);T.z=z;T.step=step+1;if(!vis[T.x][T.y][T.z]){vis[T.x][T.y][T.z]=true;q.push(T);}}
        if(z<v3){T.x=x-min(x,v3-z);T.y=y;T.z=z+min(v3-z,x);T.step=step+1;if(!vis[T.x][T.y][T.z]){vis[T.x][T.y][T.z]=true;q.push(T);}}
      }if(y>0){
        if(x<v1){T.x=x+min(v1-x,y);T.y=y-min(v1-x,y);T.z=z;T.step=step+1;if(!vis[T.x][T.y][T.z]){vis[T.x][T.y][T.z]=true;q.push(T);}}
        if(z<v3){T.x=x;T.y=y-min(v3-z,y);T.z=z+min(v3-z,y);T.step=step+1;if(!vis[T.x][T.y][T.z]){vis[T.x][T.y][T.z]=true;q.push(T);}}
      }if(z>0){
        if(x<v1){T.x=x+min(v1-x,z);T.y=y;T.z=z-min(z,v1-x);T.step=step+1;if(!vis[T.x][T.y][T.z]){vis[T.x][T.y][T.z]=true;q.push(T);}}
        if(y<v2){T.x=x;T.y=y+min(z,v2-y);T.z=z-min(z,v2-y);T.step=step+1;if(!vis[T.x][T.y][T.z]){vis[T.x][T.y][T.z]=true;q.push(T);}}
      }
    }
    return -1;
}
int main(){
    int test;scanf("%d",&test);while(test--){
    scanf("%d%d%d",&v1,&v2,&v3);
    scanf("%d%d%d",&E1,&E2,&E3);
    S.x=v1;S.y=0;S.z=0;S.step=0;
    if(E1==v1&&E2==0&&E3==0){
    cout<<0<<endl;continue;
    }
    cout<<bfs()<<endl;
    }
}



posted @ 2018-01-16 20:50  _大美  阅读(126)  评论(0编辑  收藏  举报