大家一定觉的运动以后喝可乐是一件很惬意的事情,但是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。
具体就是对于一个状态,找出a,b,c三个瓶子哪个有水。找到后,将这个瓶子向没水的瓶子里倒,如果此时的状态出现过就跳过。最后判断一下是否满足两个瓶子里水一样多并且加起来等于一共的水。
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
#define MAXN 105
typedef struct
{
int a;
int b;
int c;
int step;
} node;
node NODE(int a, int b, int c, int s)
{
node t;
t.a = a;
t.b = b;
t.c = c;
t.step = s;
return t;
}
bool judge(int i1, int i2, int i3, int a)
{
bool A = ((i1 == i2) && (i1 + i2 == a));
bool B = ((i1 == i3) && (i1 + i3 == a));
bool C = ((i2 == i3) && (i2 + i3 == a));
if(A || B || C)
return true;
else
return false;
}
bool vis[MAXN][MAXN][MAXN];
int bfs(int a, int b, int c, queue<node> &que)
{
int i1, i2, i3;
que.push(NODE(a, 0, 0, 0));
vis[a][0][0] = true;
while(!que.empty())
{
node head;
head = que.front();
if(head.a > 0)
{
i1 = max(0, head.a - (b - head.b));
i2 = min(head.b+head.a, b);
i3 = head.c;
if(!vis[i1][i2][i3])
{
vis[i1][i2][i3] = true;
que.push(NODE(i1, i2, i3, head.step+1));
// printf("%d %d %d\n", i1, i2, i3);
if(judge(i1, i2, i3, a))
return head.step+1;
}
i1 = max(0, head.a - (c - head.c));
i2 = head.b;
i3 = min(head.c+head.a, c);
if(!vis[i1][i2][i3])
{
vis[i1][i2][i3] = true;
que.push(NODE(i1, i2, i3, head.step+1));
// printf("%d %d %d\n", i1, i2, i3);
if(judge(i1, i2, i3, a))
return head.step+1;
}
}
if(head.b > 0)
{
i1 = min(head.a+head.b, a);
i2 = max(0, head.b-(a-head.a));
i3 = head.c;
if(!vis[i1][i2][i3])
{
vis[i1][i2][i3] = true;
que.push(NODE(i1, i2, i3, head.step+1));
// printf("%d %d %d\n", i1, i2, i3);
if(judge(i1, i2, i3, a))
return head.step+1;
}
i1 = head.a;
i2 = max(0, head.b-(c-head.c));
i3 = min(head.c+head.b, c);
if(!vis[i1][i2][i3])
{
vis[i1][i2][i3] = true;
que.push(NODE(i1, i2, i3, head.step+1));
// printf("%d %d %d\n", i1, i2, i3);
if(judge(i1, i2, i3, a))
return head.step+1;
}
}
if(head.c > 0)
{
i1 = min(head.a+head.c, a);
i2 = head.b;
i3 = max(0, head.c - (a-head.a));
if(!vis[i1][i2][i3])
{
vis[i1][i2][i3] = true;
que.push(NODE(i1, i2, i3, head.step+1));
// printf("%d %d %d\n", i1, i2, i3);
if(judge(i1, i2, i3, a))
return head.step+1;
}
i1 = head.a;
i2 = min(head.b+head.c, b);
i3 = max(0, head.c-(b-head.b));
if(!vis[i1][i2][i3])
{
vis[i1][i2][i3] = true;
que.push(NODE(i1, i2, i3, head.step+1));
// printf("%d %d %d\n", i1, i2, i3);
if(judge(i1, i2, i3, a))
return head.step+1;
}
}
que.pop();
}
return 0;
}
int main()
{
int a, b, c;
while(scanf("%d%d%d", &a, &b, &c) != EOF)
{
queue<node> que;
if(!a && !b && !c)
return 0;
memset(vis, false, sizeof(vis));
int ans = bfs(a, b, c, que);
if(ans == 0)
printf("NO\n");
else
printf("%d\n", ans);
}
return 0;
}