7 4 3 4 1 3 0 0 0
NO 3
解题思路:
当S为奇数时显然不满足直接pass设当前三个杯子中可口可乐的容量分别为x,y,z,则下一个状态可以分为三大类且最多六种方法:
x->y,x->z,y->x,y->z,z->x,z->y;所以枚举六个状态,宽搜 第一类由x扩展,前提x>0,第二类由y扩展,前提y>0,第三类由z扩展,前提z>0
代码:
#include <iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<cmath>
using namespace std;
int S,N,M;
const int maxn=101;
bool flag[maxn][maxn][maxn];
struct node{
int x,y,z,step;
node(int a=0,int b=0,int c=0,int ste=0):x(a),y(b),z(c),step(ste){}
};
int bfs(node s){
int ans=S/2;
queue<node>mq;
mq.push(s);
flag[s.x][s.y][s.z]=true;
while(!mq.empty()){
node head=mq.front();
mq.pop();
int x=head.x,y=head.y,z=head.z;
int step=head.step+1;
//cout<<x<<" "<<y<<" "<<z<<" "<<head.step<<endl;
if((x==ans&&y==ans)||(y==ans&&z==ans)||(x==ans&&z==ans)){
return head.step;
}
else {
if(x>0){
if(y!=N&&z!=M){
int tx1=x+y-N;//可乐由x倒向y,y最多可接收N-y,所以x变成x-(N-y),y变成N
if(!flag[tx1][N][z]){
mq.push(node(tx1,N,z,step));
flag[tx1][N][z]=true;
}
int tx2=x+z-M;//同理x倒向z;
if(!flag[tx2][y][M]){
mq.push(node(tx2,y,M,step));
flag[tx2][y][M]=true;
}
}
}
if(y>0){
if(z!=M){
int ty1=y+z-M;//可乐由y倒向z, ty1>=0表示倒完后仍有剩余,反之表示完全倒入z
if(ty1>=0&&!flag[x][ty1][M]){
flag[x][ty1][M]=true;
mq.push(node(x,ty1,M,step));
}
else if(ty1<0&&!flag[x][0][z+y]){
flag[x][0][z+y]=true;
mq.push(node(x,0,z+y,step));
}
if(!flag[x+y][0][z]){
flag[x+y][0][z]=true;
mq.push(node(x+y,0,z,step));
}
}
}
if(z>0){
if(y!=N){
int tz1=z+y-N;//同上
if(tz1>=0&&!flag[x][N][tz1]){
mq.push(node(x,N,tz1,step));
flag[x][N][tz1]=true;
}
else if(tz1<0&&!flag[x][y+z][0]){
mq.push(node(x,y+z,0,step));
flag[x][y+z][0]=true;
}
if(!flag[x+z][y][0]){
mq.push(node(x+z,y,0,step));
flag[x+z][y][0]=true;
}
}
}
}
}
return -1;
}
int main()
{
//freopen("in.txt","r",stdin);
while(scanf("%d%d%d",&S,&N,&M)!=EOF){
if(S==0&&N==0&&M==0)break;
if(S%2==1){
printf("NO\n");
continue;
}
memset(flag,0,sizeof(flag));
int ans=bfs(node(S,0,0));
if(ans==-1)printf("NO\n");
else printf("%d\n",ans);
}
return 0;
}原文地址:http://blog.csdn.net/jiangx1994/article/details/38150195