三个水杯
时间限制:
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
-
第一行一个整数N(0<N<50)表示N组测试数据
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
struct Node
{
int a,b,c;
int step;
Node()
{
step=0;
}
};
int Max[3];//刚开始水杯中最大的容量
int Cur[3];//水杯中目前的状态
int End[3];//最终水杯要到达的状态
int step;
bool b[100][100][100]= {0};
void pourWater(int i, int j)//i往j倒水
{
if(Cur[i]==0||Cur[j]==Max[j])//如果i中没有水或者杯子已经满了
return;
if(Cur[i]>Max[j]-Cur[j])//如果i中水倒不完
{
Cur[i]=Cur[i]-(Max[j]-Cur[j]);
Cur[j]=Max[j];
}
else//如果i中水不够到
{
Cur[j]=Cur[i]+Cur[j];
Cur[i]=0;
}
}
//广度优先搜索主要思想:
//刚开始的水杯中水的状态记为node,把node加入到队列中
//从这个状态开始,有6中倒水状态,分别给初始状态进行倒水,
//把符合条件的倒水后的水杯中水的状态加入到队列中,
//直到找到最后需要的状态。
void bfs()
{
queue<Node> q;
Node node,cur;
step=-1;
node.a=Max[0];
node.b=0;
node.c=0;
q.push(node);
b[node.a][node.b][node.c]=1;
while(!q.empty())
{
node = cur = q.front();
q.pop();
Cur[0]=cur.a;
Cur[1]=cur.b;
Cur[2]=cur.c;
if(Cur[0]==End[0]&&Cur[1]==End[1]&&Cur[2]==End[2])
{
step=cur.step;
break;
}
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
if(i!=j&&Cur[i]!=0&&Cur[j]!=Max[j])
{
pourWater(i,j);
if(!b[Cur[0]][Cur[1]][Cur[2]])
{
b[Cur[0]][Cur[1]][Cur[2]]=true;
cur.a=Cur[0],cur.b=Cur[1],cur.c=Cur[2];
cur.step++;
q.push(cur);
}
cur=node;
Cur[0]=cur.a;
Cur[1]=cur.b;
Cur[2]=cur.c;
}
}
}
}
}
int main()
{
int m;
cin >> m;
while(m--)
{
memset(b,0,sizeof(b));
memset(Cur,0,sizeof(Cur));
memset(End,0,sizeof(End));
cin >> Max[0] >> Max[1] >> Max[2];
cin >> End[0] >> End[1] >> End[2];
Cur[0]=Max[0];
bfs();
cout << step << endl;
}
}