大家一定觉的运动以后喝可乐是一件很惬意的事情,但是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去做, 从初始状态向下走有6种状态,分别是(S->N)、(S->M)、(N->S)、(N->M)、(M->S)、(M->N),每个状态走下去并记录下次数就行。
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
#define forn(i,n) for (int i = 0; i < n; ++i)
#define sc scanf
#define pt printf
typedef struct node{
int a;
int b;
int c;
}node;
int s, n, m, flag;
int g[105][105][105], cnt[105][105][105];
int check(node x)
{
if (x.a == x.b && x.c == 0 || x.a == x.c && x.b == 0 || x.b == x.c && x.a == 0)
return 1;
else
return 0;
}
int main()
{
while (cin >> s >> n >> m) {
if (s == 0 && n == 0 && m == 0) {
break;
}
flag = 0;
memset(g, 0, sizeof(g));
memset(cnt, 0, sizeof(cnt));
node x;
x.a = s;
x.b = 0;
x.c = 0;
g[s][0][0] = 1;
queue<node> q;
q.push(x);
while (!q.empty()) {
node t = q.front();
// pt("%d, %d, %d\n", t.a, t.b, t.c);
q.pop();
// a -> b
if (t.a + t.b > n) {
x.a = t.a + t.b - n;
x.b = n;
} else {
x.a = 0;
x.b = t.a + t.b;
}
x.c = t.c;
if (!g[x.a][x.b][x.c]) {
g[x.a][x.b][x.c] = 1;
cnt[x.a][x.b][x.c] = cnt[t.a][t.b][t.c] + 1;
if (flag = check(x))
break;
// pt("push (x) %d, %d, %d\n", x.a, x.b, x.c);
q.push(x);
}
// a -> c
if (t.a + t.c > m) {
x.a = t.a + t.c - m;
x.c = m;
} else {
x.a = 0;
x.c = t.a + t.c;
}
x.b = t.b;
if (!g[x.a][x.b][x.c]) {
g[x.a][x.b][x.c] = 1;
cnt[x.a][x.b][x.c] = cnt[t.a][t.b][t.c] + 1;
if (flag = check(x))
break;
// pt("push (x) %d, %d, %d\n", x.a, x.b, x.c);
q.push(x);
}
// b -> a
x.a = t.a + t.b;
x.b = 0;
x.c = t.c;
if (!g[x.a][x.b][x.c]) {
g[x.a][x.b][x.c] = 1;
cnt[x.a][x.b][x.c] = cnt[t.a][t.b][t.c] + 1;
if (flag = check(x))
break;
// pt("push (x) %d, %d, %d\n", x.a, x.b, x.c);
q.push(x);
}
// b -> c
if (t.b + t.c > m) {
x.b = t.b + t.c - m;
x.c = m;
} else {
x.b = 0;
x.c = t.b + t.c;
}
x.a = t.a;
if (!g[x.a][x.b][x.c]) {
g[x.a][x.b][x.c] = 1;
cnt[x.a][x.b][x.c] = cnt[t.a][t.b][t.c] + 1;
if (flag = check(x))
break;
// pt("push (x) %d, %d, %d\n", x.a, x.b, x.c);
q.push(x);
}
// c -> a
x.a = t.a + t.c;
x.b = t.b;
x.c = 0;
if (!g[x.a][x.b][x.c]) {
g[x.a][x.b][x.c] = 1;
cnt[x.a][x.b][x.c] = cnt[t.a][t.b][t.c] + 1;
if (flag = check(x))
break;
// pt("push (x) %d, %d, %d\n", x.a, x.b, x.c);
q.push(x);
}
// c -> b
if (t.b + t.c > n) {
x.c = t.b + t.c - n;
x.b = n;
} else {
x.c = 0;
x.b = t.b + t.c;
}
x.a = t.a;
if (!g[x.a][x.b][x.c]) {
g[x.a][x.b][x.c] = 1;
cnt[x.a][x.b][x.c] = cnt[t.a][t.b][t.c] + 1;
if (flag = check(x))
break;
// pt("push (x) %d, %d, %d\n", x.a, x.b, x.c);
q.push(x);
}
}
if (flag)
cout << cnt[x.a][x.b][x.c] << endl;
else
cout << "NO" << endl;
}
}