大家一定覺的運動以後喝可樂是一件很愜意的事情,但是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;
}