hdu 1495 非常可乐(bfs)

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
 
题意:有三个无刻度的瓶子互相倒水 问最少需要几次
思路:最优解当然是bfs
#include <cstdio>
#include <map>
#include <iostream>
#include<cstring>
#include<bits/stdc++.h>
#define ll long long int
#define M 6
using namespace std;
inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
int moth[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int dir[4][2]={1,0 ,0,1 ,-1,0 ,0,-1};
int dirs[8][2]={1,0 ,0,1 ,-1,0 ,0,-1, -1,-1 ,-1,1 ,1,-1 ,1,1};
const int inf=0x3f3f3f3f;
const ll mod=1e9+7;
int v[3],ans;
struct node{
    int a[3]; //当前3杯水的容量
    int step;
};
node t;
queue<node> q;
bool vis[107][107][107];
void pour(int from,int to){
    //很巧妙的倒水算法,行数最少
    int temp=t.a[from]+t.a[to];
    if(temp>=v[to]) t.a[to]=v[to];
    else t.a[to]=temp;
    t.a[from]=temp-t.a[to];
}
void bfs(){
    while(!q.empty()){
        node temp=q.front();
        q.pop();
        for(int i=0;i<3;i++)
            for(int j=0;j<3;j++)
                for(int k=0;k<3;k++){
                if(i==j||i==k||k==j)
                continue;
                if(temp.a[i]==temp.a[j]&&!temp.a[k]){
                    ans=temp.step;
                    return ;
                }
            }
        for(int i=0;i<3;i++)
            for(int j=0;j<3;j++){
                if(i==j)
                continue;
                t=temp;
                pour(i,j); //从i到给j
                if(!vis[t.a[0]][t.a[1]][t.a[2]]){
                    t.step++;
                    vis[t.a[0]][t.a[1]][t.a[2]]=1;
                    q.push(t);
                }
            }
    }
}
int main(){
    ios::sync_with_stdio(false);
    while(cin>>v[0]>>v[1]>>v[2]){
        if(!v[0]&&!v[1]&&!v[2])
        break;
        memset(vis,0,sizeof(vis));
        if(v[0]%2!=0)
        cout<<"NO"<<endl;
        else{
            node t; t.a[0]=v[0]; t.a[1]=0; t.a[2]=0; t.step=0;
            vis[v[0]][0][0]=1;
            q.push(t);
            ans=inf;
            bfs();
            if(ans!=inf)
            cout<<ans<<endl;
            else cout<<"NO"<<endl;
            while(!q.empty())
            q.pop();
        }
    }
}

 

posted @ 2019-02-18 16:35  WAKBGAN  阅读(157)  评论(0编辑  收藏  举报