当前位置: 代码迷 >> 综合 >> HDU 1495——非常可乐【隐式BFS】
  详细解决方案

HDU 1495——非常可乐【隐式BFS】

热度:78   发布时间:2023-12-16 23:11:34.0

题目传送门

非常可乐

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可以解决

AC代码:

#include <iostream>
#include <vector>
#include <utility>
#include <cstring>
#include <algorithm>
#include <map>
#include <queue>
#include <stack>
#include <cstdio>
#include <set>
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
typedef long long ll;#define INT_MAX 0XFFFFFFF#define N 105
int tong[3];
int sum;
int ans;
bool vis[N][N][N];
struct node {
    int v[3];int count;node(int a, int b, int c, int d) {
    v[0] = a, v[1] = b, v[2] = c, count = d;}node() {
    v[0] = v[1] = v[2] = count = 0;}
}temp;void pour(int a, int b) {
    	// a -> bint sum = temp.v[a] + temp.v[b];if (sum >= tong[b])temp.v[b] = tong[b];elsetemp.v[b] = sum;temp.v[a] = sum - temp.v[b];}
bool bfs() {
    queue<node>q;q.push(node(tong[0], 0, 0, 0));while (q.size()) {
    node now = q.front();q.pop();vis[now.v[0]][now.v[1]][now.v[2]] = true;if ((now.v[1] == now.v[2] && now.v[2] == sum / 2) || (now.v[1] == now.v[0] && now.v[0] == sum / 2) || (now.v[0] == now.v[2] && now.v[2] == sum / 2)) {
    ans = now.count;return true;}for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
    if (i == j)continue;temp = now;pour(i, j);if (temp.v[0] >= 0 && temp.v[1] >= 0 && temp.v[2] >= 0 && !vis[temp.v[0]][temp.v[1]][temp.v[2]]) {
    temp.count = now.count + 1;q.push(temp);}}}}return false;
}int main() {
    while (cin >> tong[0] >> tong[1] >> tong[2], tong[0] && tong[1] && tong[2]) {
    sum = tong[0];if (sum & 1) {
    cout << "NO" << endl;continue;}else {
    memset(vis, false, sizeof(vis));if (bfs())cout << ans << endl;elsecout << "NO" << endl;}}return 0;
}