0
点赞
收藏
分享

微信扫一扫

HDU 1495 非常可乐(bfs)

大家一定觉的运动以后喝可乐是一件很惬意的事情,但是seeyou却不这么认为。因为每次当seeyou买了可乐以后,阿牛就要求和seeyou一起分享这一瓶可乐,而且一定要喝的和seeyou一样多。但seeyou的手中只有两个杯子,它们的容量分别是N 毫升和M 毫升 可乐的体积为S (S<101)毫升 (正好装满一瓶) ,它们三个之间可以相互倒可乐 (都是没有刻度的,且 S==N+M,101>S>0,N>0,M>0) 。聪明的ACMER你们说他们能平分吗?如果能请输出倒可乐的最少的次数,如果不能输出"NO"。
Input
三个整数 : S 可乐的体积 , N 和 M是两个杯子的容量,以"0 0 0"结束。
Output
如果能平分的话请输出最少要倒的次数,否则输出"NO"。
Sample Input
7 4 3
4 1 3
0 0 0
Sample Output
NO
3

就是模拟三个杯子相互倒,广搜中一共六种情况。需要注意的是倒的过程中的变量赋值需要有先后顺序。再就是最后判断是否可以相等,是任意两个杯子中的量相等就可以了,不需要非得那两个空杯子中的量相等。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

int book[105][105][105];
typedef struct{
int a, b, c;
int step;
}node;
int s, n, m;

int bfs()
{
queue<node> q;
node t;
t.a=s, t.b=0, t.c=0;
t.step=0;
q.push(t);
book[s][0][0]=1;

while (!q.empty()){
node tmp=q.front();
q.pop();
if ((tmp.b==s/2&&tmp.c==s/2) || (tmp.a==s/2&&tmp.c==s/2) || (tmp.a==s/2&&tmp.b==s/2))
return tmp.step;

t.a=tmp.a; t.b=tmp.b; t.c=tmp.c;
t.step=tmp.step+1;
//s n 向s瓶倒
if (t.a+t.b>s){
t.b=t.a+t.b-s;
t.a=s;
t.c=t.c;
}else{
t.a+=t.b;
t.b=0;
t.c=t.c;
}
if (book[t.a][t.b][t.c]==0){
q.push(t);
book[t.a][t.b][t.c]=1;
}
t.a=tmp.a; t.b=tmp.b; t.c=tmp.c;
t.step=tmp.step+1;
//s n 向n瓶倒
if (t.a+t.b>n){
t.a=t.a+t.b-n;
t.b=n;
t.c=t.c;
}else{
t.b+=t.a;
t.a=0;
t.c=t.c;
}
if (book[t.a][t.b][t.c]==0){
q.push(t);
book[t.a][t.b][t.c]=1;
}
t.a=tmp.a; t.b=tmp.b; t.c=tmp.c;
t.step=tmp.step+1;
//s m向s瓶倒
if (t.a+t.c>s){
t.c=t.a+t.c-s;
t.a=s;
t.b=t.b;
}else{
t.a+=t.c;
t.c=0;
t.b=t.b;
}
if (book[t.a][t.b][t.c]==0){
q.push(t);
book[t.a][t.b][t.c]=1;
}
t.a=tmp.a; t.b=tmp.b; t.c=tmp.c;
t.step=tmp.step+1;
//s m向m瓶倒
if (t.a+t.c>m){
t.a=t.a+t.c-m;
t.c=m;
t.b=t.b;
}else{
t.c+=t.a;
t.a=0;
t.b=t.b;
}
if (book[t.a][t.b][t.c]==0){
q.push(t);
book[t.a][t.b][t.c]=1;
}
t.a=tmp.a; t.b=tmp.b; t.c=tmp.c;
t.step=tmp.step+1;
//n m向n瓶倒
if (t.b+t.c>n){
t.c=t.b+t.c-n;
t.b=n;
t.a=t.a;
}else{
t.b+=t.c;
t.c=0;
t.a=t.a;
}
if (book[t.a][t.b][t.c]==0){
q.push(t);
book[t.a][t.b][t.c]=1;
}
t.a=tmp.a; t.b=tmp.b; t.c=tmp.c;
t.step=tmp.step+1;
//n m向m瓶倒
if (t.b+t.c>m){
t.b=t.b+t.c-m;
t.c=m;
t.a=t.a;
}else{
t.c+=t.b;
t.b=0;
t.a=t.a;
}
if (book[t.a][t.b][t.c]==0){
q.push(t);
book[t.a][t.b][t.c]=1;
}
}
return -1;
}
int main()
{
while (scanf("%d%d%d", &s, &n, &m)!=EOF){
if (s==0 && n==0 && m==0)
break;
if (s%2==1){
printf("NO\n");
continue;
}
memset(book, 0, sizeof(book));
int ans=bfs();
if (ans==-1)
printf("NO\n");
else
printf("%d\n", ans);
}
return 0;
}


举报

相关推荐

0 条评论