是一道广搜的题,,就是把3个水杯的6中状态一一枚举出来,由哪个状态先打到目的状态,,,即是最少步数。中间要判断一下某个状态是否出现,若出现过就不在进入队列,因为同种状态后出现的步数比先出现的步数大。。。。题目:
-
输入
-
第一行一个整数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 <iostream>
#include <deque>
#include <string.h>
using namespace std;
struct cup
{
int v[3];
int step;
}first,mid,last;
deque<cup> ss;
bool record[1000005];
int v1,v2,v3;
int vv[3];
bool panduan()
{
if(!record[last.v[0]*10000+last.v[1]*100+last.v[2]])
{
record[last.v[0]*10000+last.v[1]*100+last.v[2]]=true;
return true;
}
return false;
}
void move(int x,int y,int z)
{
if(mid.v[x]+mid.v[y]<vv[y])
{
last.v[x]=0;
last.v[y]=mid.v[x]+mid.v[y];
last.v[z]=mid.v[z];
last.step=mid.step+1;
if(panduan())
ss.push_back(last);
}
else
{
last.v[x]=mid.v[x]+mid.v[y]-vv[y];
last.v[y]=vv[y];
last.v[z]=mid.v[z];
last.step=mid.step+1;
if(panduan())
ss.push_back(last);
}
}
int find()
{
ss.push_back(first);
while(!ss.empty())
{
mid.v[0]=ss.front().v[0];
mid.v[1]=ss.front().v[1];
mid.v[2]=ss.front().v[2];
mid.step=ss.front().step;
ss.pop_front();
if(mid.v[0]==v1&&mid.v[1]==v2&&mid.v[2]==v3)
return mid.step;
else
{
if(mid.v[0])
{
move(0,1,2);
move(0,2,1);
}
if(mid.v[1])
{
move(1,0,2);
move(1,2,0);
}
if(mid.v[2])
{
move(2,1,0);
move(2,0,1);
}
}
}
return -1;
}
int main()
{
int kk;
cin>>kk;
while(kk--)
{
memset(record,false,sizeof(record));
//int vv[3];
cin>>vv[0]>>vv[1]>>vv[2];
cin>>v1>>v2>>v3;
first.v[0]=vv[0];
first.v[1]=0;
first.v[2]=0;
first.step=0;
if(v1+v2+v3!=vv[0])
cout<<"-1"<<endl;
else
{
int x=find();
cout<<x<<endl;
}
ss.clear();
}
return 0;
}