非常可樂
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 -> b
int sum = temp.v[a] + temp.v[b];
if (sum >= tong[b])
temp.v[b] = tong[b];
else
temp.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;
else
cout << "NO" << endl;
}
}
return 0;
}