HDUOJ1495非常可乐
Problem Description
大家一定觉的运动以后喝可乐是一件很惬意的事情,但是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
思路
一个,有点有趣的题
(碎碎念time:粗略的看一眼以为是暴力过的水题那种,然后因为是搜索专题的就感觉是BFS吖
然后初始思路就在想应该按怎么倒哇,想到按照每次减去n或m那样,但是不太行啊,完了以后其实我是后来网上搜了题解看了思路写出来的)
把三个瓶子的状态作为一个节点
然后分为每个瓶子分别往其他两个倒的共六种情况(六个方向)
每一个倒还可以分为能全倒入和不能全倒入
AC代码
//BFS?
#include<cstdio>
#include<cstring>
#include<queue>
#include<iostream>
using namespace std;
struct node
{
int a,b,c;
int step;//a,b,c 对应S,N,M 装的cola的量
}S,now,nex;
queue<node> q;
int s,n,m;
bool vis[101][101][101];//三个瓶子分别装多少时的状态之前有没有出现过
bool jud(int a, int b, int c)
{
if(2 * a == s && (a == b || a == c))return 1;
return 0;
}
//void pour(int now.a, int now.b, int now.c, int nex.a, int nex.b, int nex.c)//a倒入b
//{
// nex.c = now.c;
// if(now.a >= (n - now.b))//a不能全倒进b
// {
// nex.a = now.a - (n - now.b);
// nex.b = n;
// }
// else //a能全倒进b
// {
// nex.a = 0;
// nex.b = now.b + now.a;
// }
// if(!vis[nex.a][nex.b][nex.c])
// {
// q.push(nex);
// vis[nex.a][nex.b][nex.c] = 1;
// }
//}
int bfs()//三个瓶子分别往其他两个倒的六种情况
{
while(!q.empty())
{
now=q.front();
q.pop();
if(jud(now.a, now.b, now.c)) return now.step;
if(jud(now.b, now.a, now.c)) return now.step;
if(jud(now.c, now.b, now.a)) return now.step;//出现了平均的情况
nex.step=now.step+1;
//a->b:
if(now.b<n)
{
nex.c=now.c;
if(now.a >= n-now.b) nex.a=now.a-(n-now.b), nex.b=n;
else nex.a=0, nex.b=now.b+now.a;
if(!vis[nex.a][nex.b][nex.c])
{
q.push(nex);
vis[nex.a][nex.b][nex.c]=1;
}
}
//a->c:
if(now.c<m)
{
nex.b=now.b;
if(now.a >= m-now.c) nex.a=now.a-(m-now.c), nex.c=m;
else nex.a=0, nex.c=now.c+now.a;
if(!vis[nex.a][nex.b][nex.c])
{
q.push(nex);
vis[nex.a][nex.b][nex.c]=1;
}
}
//b->c:
if(now.c<m)
{
nex.a=now.a;
if(now.b >= m-now.c) nex.b=now.b-(m-now.c), nex.c=m;
else nex.b=0, nex.c=now.c+now.b;
if(!vis[nex.a][nex.b][nex.c])
{
q.push(nex);
vis[nex.a][nex.b][nex.c]=1;
}
}
//b->a:
if(now.a<s)
{
nex.c=now.c;
if(now.b >= s-now.a) nex.a=s, nex.b=now.b-(s-now.a);
else nex.a=now.a+now.b, nex.b=0;
if(!vis[nex.a][nex.b][nex.c])
{
q.push(nex);
vis[nex.a][nex.b][nex.c]=1;
}
}
//c->a:
if(now.a<s)
{
nex.b=now.b;
if(now.c >= s-now.a) nex.a=s, nex.c=now.c-(s-now.a);
else nex.a=now.a+now.c, nex.c=0;
if(!vis[nex.a][nex.b][nex.c])
{
q.push(nex);
vis[nex.a][nex.b][nex.c]=1;
}
}
//c->b:
if(now.b<n)
{
nex.a=now.a;
if(now.c >= n-now.b) nex.b=n, nex.c=now.c-(n-now.b);
else nex.b=now.b+now.c, nex.c=0;
if(!vis[nex.a][nex.b][nex.c])
{
q.push(nex);
vis[nex.a][nex.b][nex.c]=1;
}
}
}
return -1;
}
int main()
{
while(cin>>s>>n>>m && (s+n+m))
{
memset(vis,0,sizeof(vis));
while(!q.empty())
q.pop();
S.a=s;
S.b=0;
S.c=0;
S.step=0;
q.push(S);
vis[S.a][S.b][S.c]=1;
int ans=bfs();
if(ans >= 0)cout<<ans<<endl;
else cout<<"NO"<<endl;
}
}