您的位置:首页 > 其它

HDU 1495 非常可乐(广搜BFS) (M)

2017-07-06 10:45 357 查看


题意:相当于泊松分酒问题的简化版 三个杯子  容量为a,b,c  且a==b+c,一开始的时候a装满,求最少步数均分,如果不能输出NO

思路:广搜  每次都搜索6个操作 就是他们互相倒来倒去  用vis数组来判断这个状态是否已经出现过了进行剪枝

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
#define maxn 150
bool vis[maxn][maxn];
int a,b,c;
int ans[maxn][maxn];
bool check(int x,int y,int z)//检查是否已经均分
{
if(x==y&&z==0)return true;
if(x==z&&y==0)return true;
if(z==y&&x==0)return true;
return false;
}
void push(int& fx,int x,int &fy)//fy 倒入 fx x为容量
{
if(fx+fy>=x)
{
fy=fy-(x-fx);
fx=x;

}
else
{
fx=fx+fy;
fy=0;
}
}
void bfs()
{
int x,y,z;
x=a,y=0,z=0;
queue<pair<int,int> >q;
q.push(make_pair(0,0));
vis[y][z]=true;
ans[y][z]=0;
while(!q.empty())
{
pair<int ,int >p;
p=q.front();
q.pop();
y=p.first;
z=p.second;
x=a-y-z;
if(check(x,y,z))
{
printf("%d\n",ans[y][z]);
return;
}
push(x,a,y);//y 倒入 x
if(!vis[y][z])
{
vis[y][z]=true;
ans[y][z]=ans[p.first][p.second]+1;

q.push(make_pair(y,z));
}
y=p.first;
z=p.second;
x=a-y-z;
push(x,a,z);//z倒入x
if(!vis[y][z])
{
vis[y][z]=true;
ans[y][z]=ans[p.first][p.second]+1;
q.push(make_pair(y,z));
}
y=p.first;
z=p.second;
x=a-y-z;
push(y,b,x);//x倒入y
if(!vis[y][z])
{
vis[y][z]=true;
ans[y][z]=ans[p.first][p.second]+1;

q.push(make_pair(y,z));
}
y=p.first;
z=p.second;
x=a-y-z;
push(y,b,z);//z倒入y
if(!vis[y][z])
{
vis[y][z]=true;
ans[y][z]=ans[p.first][p.second]+1;
q.push(make_pair(y,z));
}
y=p.first;
z=p.second;
x=a-y-z;
push(z,c,x);//x倒入z
if(!vis[y][z])
{
vis[y][z]=true;
ans[y][z]=ans[p.first][p.second]+1;
q.push(make_pair(y,z));
}
y=p.first;
z=p.second;
x=a-y-z;
push(z,c,y);//y倒入z
if(!vis[y][z])
{
vis[y][z]=true;
ans[y][z]=ans[p.first][p.second]+1;
q.push(make_pair(y,z));
}
}
printf("NO\n");
}
int main()
{
while(~scanf("%d%d%d",&a,&b,&c))
{
if(a==0&&b==0&&c==0)
{
break;
}
memset(vis,0,sizeof vis);
memset(ans,0,sizeof ans);
bfs();
}
return 0;
}

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