一道经典的BFS问题
题目描述
大家一定觉的运动以后喝可乐是一件很惬意的事情,但是seeyou却不这么认为。因为每次当seeyou买了可乐以后,阿牛就要求和seeyou一起分享这一瓶可乐,而且一定要喝的和seeyou一样多。但seeyou的手中只有两个杯子,它们的容量分别是N 毫升和M 毫升 可乐的体积为S (S<101)毫升 (正好装满一瓶) ,它们三个之间可以相互倒可乐 (都是没有刻度的,且 S==N+M,101>S>0,N>0,M>0) 。聪明的ACMER你们说他们能平分吗?如果能请输出倒可乐的最少的次数,如果不能输出"NO"。
输入
三个整数 : S 可乐的体积 , N 和 M是两个杯子的容量,以"0 0 0"结束。
输出
如果能平分的话请输出最少要倒的次数,否则输出"NO"。
样例输入
7 4 3
4 1 3
0 0 0
样例输出
NO
3
分析
使用BFS,如果符合条件则入队,找到最终条件返回1,队空返回-1。
#include<bits/stdc++.h>
using namespace std;
bool visited[101][101][101];//判断是否被访问过
struct node{
//三个罐子当前情况及已倒次数
int s,n,m,num;
};
int s,n,m;
int BFS(){
//如果是奇数,直接False
if(s%2 == 1)
return -1;
memset(visited,false,sizeof(visited));
queue<node> que;
node q;
q.s = s;
q.n = 0;
q.m = 0;
q.num = 0;
visited[s][n][m] = true;
que.push(q);
while(!que.empty()){
q = que.front();
que.pop();
if((q.s == q.m &&q.n == 0)||(q.s == q.n&&q.m == 0)||(q.n == q.m&&q.s == 0))
//已经平分,返回倾倒次数
return q.num;
node tmp;
//s->n
if(q.s&&n - q.n > 0){//后面是判断n不满的情况
if(q.s > n - q.n){
tmp.s = q.s - (n-q.n);
tmp.n = n;
tmp.m = q.m;
}
else{
tmp.n = q.n + q.s;
tmp.s = 0;
tmp.m = q.m;
}
if(visited[tmp.s][tmp.n][tmp.m] == false){
visited[tmp.s][tmp.n][tmp.m] = true;
tmp.num = q.num + 1;
que.push(tmp);
}
}
//s->m
if(q.s&&m - q.m > 0){
if(q.s > m - q.m){
tmp.s = q.s - (m-q.m);
tmp.m = m;
tmp.n = q.n;
}
else{
tmp.m = q.m + q.s;
tmp.s = 0;
tmp.n = q.n;
}
if(visited[tmp.s][tmp.n][tmp.m] == false){
visited[tmp.s][tmp.n][tmp.m] = true;
tmp.num = q.num+1;
que.push(tmp);
}
}
//n->m
if(q.n&&m - q.m > 0){
if(q.n > m - q.m){
tmp.n = q.n - (m-q.m);
tmp.m = m;
tmp.s = q.s;
}
else{
tmp.m = q.m + q.n;
tmp.n = 0;
tmp.s = q.s;
}
if(visited[tmp.s][tmp.n][tmp.m] == false){
visited[tmp.s][tmp.n][tmp.m] = true;
tmp.num = q.num+1;
que.push(tmp);
}
}
//n->s
if(q.n&&s - q.s > 0){
if(q.n > s - q.s){
tmp.n = q.n - (s-q.s);
tmp.s = s;
tmp.m = q.m;
}
else{
tmp.s = q.s + q.n;
tmp.n = 0;
tmp.m = q.m;
}
if(visited[tmp.s][tmp.n][tmp.m] == false){
visited[tmp.s][tmp.n][tmp.m] = true;
tmp.num = q.num+1;
que.push(tmp);
}
}
//m->s
if(q.m&&s - q.s > 0){
if(q.m > s - q.s){
tmp.m = q.m - (s-q.s);
tmp.s = s;
tmp.n = q.n;
}
else{
tmp.s = q.s + q.m;
tmp.m = 0;
tmp.n = q.n;
}
if(visited[tmp.s][tmp.n][tmp.m] == false){
visited[tmp.s][tmp.n][tmp.m] = true;
tmp.num = q.num+1;
que.push(tmp);
}
}
//m->n
if(q.m&&n - q.n > 0){
if(q.m > n - q.n){
tmp.m = q.m - (n-q.n);
tmp.n = n;
tmp.s = q.s;
}
else{
tmp.n = q.n + q.m;
tmp.m = 0;
tmp.s = q.s;
}
if(visited[tmp.s][tmp.n][tmp.m] == false){
visited[tmp.s][tmp.n][tmp.m] = true;
tmp.num = q.num+1;
que.push(tmp);
}
}
}
return -1;
}
int main(){
int ans;
while(cin>>s>>n>>m){
if(s == 0)
break;
ans = BFS();
if(ans == -1)
cout<<"NO"<<endl;
else cout<<ans<<endl;
}
return 0;
}