非常可乐
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 17457 Accepted Submission(s): 7092
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
Author
seeyou
vis[][]数组表示a,b瓶中可乐是否存在,分6种情况(s->a,s->b,a->b,b->a,a->s,b->s),进行bfs,当a,b到s的一半时输出步数
#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#include <cmath>
using namespace std;
int n;
int m;
int s;
int vis[105][105];
typedef struct node {
int s;
int a;
int b;
int t;
} node;
int bfs() {
queue<node> q;
node now;
node to;
memset(vis,0,sizeof(vis));
now.s = s;
now.a = 0;
now.b = 0;
now.t = 0;
q.push(now);
vis[now.a][now.b] = 1;
while(!q.empty()) {
now = q.front();
q.pop();
if(now.s == s/2 && now.a == s/2) {
return now.t;
}
if(now.s && now.a != n) { //s->a
int c = n - now.a;
if(now.s >= c) {
to.a = n;
to.s = now.s - c;
} else {
to.a = now.a + now.s;
to.s = 0;
}
to.b = now.b;
to.t = now.t + 1;
if(!vis[to.a][to.b]) {
q.push(to);
vis[to.a][to.b] = 1;
}
}
if(now.s && now.b != m) { //s->b
int c = m - now.b;
if(now.s >= c) {
to.b = m;
to.s = now.s - c;
} else {
to.b = now.b + now.s;
to.s = 0;
}
to.a = now.a;
to.t = now.t + 1;
if(!vis[to.a][to.b]) {
q.push(to);
vis[to.a][to.b] = 1;
}
}
if(now.a && now.s != s) { //a->s
int c = s - now.s;
if(now.a >= c) {
to.s = s;
to.a = now.a - c;
} else {
to.s = now.a + now.s;
to.a = 0;
}
to.b = now.b;
to.t = now.t + 1;
if(!vis[to.a][to.b]) {
q.push(to);
vis[to.a][to.b] = 1;
}
}
if(now.a && now.b != m) { //a->b
int c = m - now.b;
if(now.a >= c) {
to.b = m;
to.a = now.a - c;
} else {
to.b = now.b + now.a;
to.a = 0;
}
to.s = now.s;
to.t = now.t + 1;
if(!vis[to.a][to.b]) {
q.push(to);
vis[to.a][to.b] = 1;
}
}
if(now.b && now.a != n) {//b->a
int c = n - now.a;
if(now.b >= c) {
to.a = n;
to.b = now.b - c;
} else {
to.a = now.b + now.a;
to.b = 0;
}
to.s = now.s;
to.t = now.t + 1;
if(!vis[to.a][to.b]) {
q.push(to);
vis[to.a][to.b]=1;
}
}
if(now.b && now.s != s) {//b->s
int c = s - now.s;
if(now.b >= c) {
to.s = s;
to.b = now.b - c;
} else {
to.s = now.s + now.b;
to.b = 0;
}
to.a = now.a;
to.t = now.t + 1;
if(!vis[to.a][to.b]) {
q.push(to);
vis[to.a][to.b] = 1;
}
}
}
return 0;
}
int main(){
while(cin >> s >> n >> m) {
if(!s && !n && !m) {
break;
}
if(s % 2) {
cout << "NO" << endl;
}
if(m > n) {
swap(m,n);
}
int res = bfs();
if(res) {
cout << res << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}