思路
最难在于想到这道题是BFS,想到之后只有六种情况就很好理解了。
代码
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<queue>
using namespace std;
int a,b,s;
struct shui
{int count;int ha,hb,hs;
}t,t1;
int min(int x,int y)
{return x<y?x:y;
}
bool vis[1000][1000];
bool mark;
struct shui bfs(int ha,int hb,int hs,int count)
{queue<struct shui> q;t.hs=s;t.ha=0;t.hb=0;t.count=0;q.push(t);vis[t.ha][t.hb]=true;while(!q.empty()){t1=q.front();q.pop();if(t1.hs==t1.ha&&t1.ha==s/2&&t1.hb==0){mark=true;return t1;}if(t1.hs&&t1.ha!=a)//瓶子s倒到杯子a{t.count=t1.count+1;t.ha=t1.ha+min(a-t1.ha,t1.hs);//a-t1.ha是瓶子中最多能倒的,t1.hs是最多能倒的t.hs=t1.hs-min(a-t1.ha,t1.hs);t.hb=t1.hb;if(t.hs==t.ha&&t.ha==s/2&&t.hb==0){ //printf("z1 %d %d %d %d\n",t.ha,t.hb,t.hs,t.count);mark=true;return t;}if(!vis[t.ha][t.hb]){//printf("b1 %d %d %d %d\n",t.ha,t.hb,t.hs,t.count);vis[t.ha][t.hb]=true;q.push(t);}}if(t1.hs&&t1.hb!=b){t.count=t1.count+1;t.hb=t1.hb+min(b-t1.hb,t1.hs);t.hs=t1.hs-min(b-t1.hb,t1.hs);t.ha=t1.ha;if(t.hs==t.ha&&t.ha==s/2&&t.hb==0){ mark=true;return t;}if(!vis[t.ha][t.hb]){vis[t.ha][t.hb]=true;q.push(t);}}if(t1.ha&&t1.hs!=s)//a{t.count=t1.count+1;t.hs=t1.hs+min(s-t1.hs,t1.ha);t.ha=t1.ha-min(s-t1.hs,t1.ha);t.hb=t1.hb;if(t.hs==t.ha&&t.ha==s/2&&t.hb==0){mark=true;return t;}if(!vis[t.ha][t.hb]){ vis[t.ha][t.hb]=true;q.push(t);}}if(t1.ha&&t1.hb!=b){t.count=t1.count+1;t.hb=t1.hb+min(b-t1.hb,t1.ha);t.ha=t1.ha-min(b-t1.hb,t1.ha);t.hs=t1.hs;if(t.hs==t.ha&&t.ha==s/2&&t.hb==0){ mark=true;return t;}if(!vis[t.ha][t.hb]){ vis[t.ha][t.hb]=true;q.push(t);}}if(t1.hb&&t1.ha!=a){t.count=t1.count+1;t.ha=t1.ha+min(a-t1.ha,t1.hb);t.hb=t1.hb-min(a-t1.ha,t1.hb);t.hs=t1.hs;if(t.hs==t.ha&&t.ha==s/2&&t.hb==0){ mark=true;return t;}if(!vis[t.ha][t.hb]){ vis[t.ha][t.hb]=true;q.push(t);}}if(t1.hb&&t1.hs!=s){t.count=t1.count+1;t.hs=t1.hs+min(s-t1.hs,t1.hb);t.hb=t1.hb-min(s-t1.hs,t1.hb);t.ha=t1.ha;if(t.hs==t.ha&&t.ha==s/2&&t.hb==0){mark=true;return t;}if(!vis[t.ha][t.hb]){ vis[t.ha][t.hb]=true;q.push(t);}}}return t;
}
int main()
{struct shui p;while(~scanf("%d%d%d",&s,&a,&b)){if(a<b){int t;t=a;a=b;b=t;}memset(vis,false,sizeof(vis));mark=false;if(a==0&&b==0&&s==0)break;p=bfs(0,0,s,0);if(mark) printf("%d\n",p.count);elseprintf("NO\n");}return 0;
}