kuangbin专题一 简单搜索 非常可乐(HDU-1495)

发布时间 2023-04-16 00:43:10作者: Amαdeus

非常可乐

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

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求最短步数模型,枚举杯子i(0 < i < 3)倒入杯子j(0 < j < 3),且i != j。注意一下细节处理即可,基本套用模板,也是简单题。

/*   一切都是命运石之门的选择  El Psy Kongroo  */
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<cmath>
#include<functional>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<int, pii> piii;
typedef pair<double, double> pdd;
typedef pair<string, pii> psi;
typedef __int128 int128;
#define PI acos(-1.0)
#define x first
#define y second
const int inf = 0x3f3f3f3f, mod = 1e9 + 7;


struct node{
    int v[3];    //存储三个杯子状态
    int d;       //记录到达状态的操作步数
};
const int N = 110;
bool vis[N][N][N];  //记录状态是否被访问过
int w[3];

int bfs(){
    memset(vis, 0, sizeof(vis));
    queue<node> q; q.push({w[0], 0, 0, 0});
    vis[w[0]][0][0] = true;

    while(!q.empty()){
        node t = q.front();
        q.pop();

        int tmp[3], a = t.v[0], b = t.v[1], c = t.v[2];
        if(a == b && c == 0 || a == c && b == 0 || b == c && a == 0) return t.d;
        
        //枚举 从杯子i倒入杯子j 
        for(int i = 0; i < 3; i ++ )
            for(int j = 0; j < 3; j ++ ){
                tmp[0] = a, tmp[1] = b, tmp[2] = c;
                if(i == j || tmp[i] == 0 || tmp[j] == w[j]) continue; //同一个杯子 或 杯子i为空 或 杯子j为满
                int cur = min(w[j] - tmp[j], tmp[i]);   //最多能倒的体积
                tmp[i] -= cur, tmp[j] += cur;

                if(vis[tmp[0]][tmp[1]][tmp[2]]) continue;
                q.push({tmp[0], tmp[1], tmp[2], t.d + 1});
                vis[tmp[0]][tmp[1]][tmp[2]] = true; 
            }
    }

    return -1;
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);

    while(cin >> w[0] >> w[1] >> w[2] && (w[0] || w[1] || w[2])){
        if(w[0] & 1){
            cout << "NO" << endl;
            continue;
        }
        int res = bfs();
        if(res == -1) cout << "NO" << endl;
        else cout << res << endl;
    }

    return 0;
}