您的位置:首页 > 其它

nyoj 三个水杯 (BFS )

2015-04-25 12:23 183 查看
解题思路:

有三种容量的杯子(v1, v2, v3),记录每一个杯子里水的体积为(s1, s2, s3),每一个杯子的剩余容量为水杯里的水在相互倾倒的时候会有以下的两种情况

1、一个杯子a所剩的容量(大小为va-sa)比水杯b要倒过来的水(大小为sb)的时候可以将b里的水全部倒到a中,最终a中水的体积为sa+sb, b中水的体积为0;



2、一个杯子a所剩的容量(大小为va-sa)比水杯b要倒过来的水(大小为sb)的时候,b中水的体积为b中水的体积减去a的剩余容量sb=sb-(va-sa),a中最终水的体积为a杯子的容量sa=va;



#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
#define MAX 110
bool vis[MAX][MAX][MAX];
int dx[]={0,0,1,1,2,2};
int dy[]={1,2,0,2,0,1};
struct Node
{
int v[3], num;
};
int v[3];
int e[3];
queue<Node>q;
int main()
{
Node tmp;
int T;
cin>>T;
while (T--)
{
cin>>v[0]>>v[1]>>v[2]>>e[0]>>e[1]>>e[2];
memset(vis, 0, sizeof(vis));
while (!q.empty())
q.pop();
tmp.v[0] = v[0], tmp.v[1]=0, tmp.v[2]=0,tmp.num=0;
q.push(tmp);
vis[v[0]][0][0] = 1;
int flag = 0;
while (!q.empty())
{
tmp = q.front();
q.pop();
if (tmp.v[0]==e[0] && tmp.v[1]==e[1] && tmp.v[2] == e[2])
{
cout<<tmp.num<<endl;
flag = 1;
break;
}
tmp.num++;
for (int i=0; i<6; i++)
{
Node t = tmp;
if (v[dx[i]]-tmp.v[dx[i]] > tmp.v[dy[i]])//剩余容量比要倒的水大
{
t.v[dx[i]] = tmp.v[dx[i]] + tmp.v[dy[i]];
t.v[dy[i]] = 0;
if (!vis[t.v[0]][t.v[1]][t.v[2]])
{
vis[t.v[0]][t.v[1]][t.v[2]] = 1;
q.push(t);
}
}
else if (v[dx[i]]-tmp.v[dx[i]] < tmp.v[dy[i]])//剩余容量比要倒的水小
{
t.v[dy[i]] = tmp.v[dy[i]] - (v[dx[i]]-tmp.v[dx[i]]);
t.v[dx[i]] = v[dx[i]];
if (!vis[t.v[0]][t.v[1]][t.v[2]])
{
vis[t.v[0]][t.v[1]][t.v[2]] = 1;
q.push(t);
}
}
}
}
if (!flag)
cout<<"-1"<<endl;

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: