参见小白书130页-131页,关键是在状态的存储,一开始用L*100+M*10+S存储每一个状态,L,M,S分别表示第一个第二个第三个杯子所含的可乐的量,不能过,因为这样的编码有重复。
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 105;
typedef int state[3];
int L,M,S;
state queues[10500];
int vis[N][N][N];
int dis[N][N][N];
int fronts,rear;
void cal(int &l,int &m,int &s,int n)
{
int all;
switch(n)
{
case 0:
all = M - m;
if(all>l){m += l;l = 0;}
else {l-=all;m = M;}break;
case 1:
all = S - s;
if(all>l){s += l;l = 0;}
else {l-=all;s = S;}break;
case 2:
all = L - l;
if(all>m){l += m;m = 0;}
else {m-=all;l = L;}break;
case 3:
all = S - s;
if(all>m){s += m;m = 0;}
else {m-=all;s = S;}break;
case 4:
all = L - l;
if(all>s){l += s;s = 0;}
else {s-=all;l = L;}break;
case 5:
all = M - m;
if(all>s){m += s;s = 0;}
else {s-=all;m = M;}break;
}
}
bool chack(state u)
{
int l = u[0],m = u[1],s = u[2];
if(l == m && l+m == L)return 1;
else if(l == s && l+s == L)return 1;
else if(m == s && m+s == L)return 1;
else return 0;
}
int bfs()
{
fronts = 0;rear = 1;
queues[fronts][0] = L;queues[fronts][1] = queues[fronts][2] = 0;
vis[L][0][0] = 1;
dis[L][0][0] = 0;
while(rear > fronts){
state& u = queues[fronts++];
if(chack(u))return dis[u[0]][u[1]][u[2]];
int l = u[0];
int m = u[1];
int s = u[2];
for(int i = 0;i<6;i++){
int newl = l,newm = m,news = s;
cal(newl,newm,news,i);
if(!vis[newl][newm][news]){
queues[rear][0] = newl;queues[rear][1] = newm;queues[rear][2] = news;rear++;
vis[newl][newm][news] = 1;
dis[newl][newm][news] = dis[l][m][s] + 1;
}
}
}
return 0;
}
int main()
{
while(scanf("%d%d%d",&L,&M,&S) == 3){
if(L == 0 && M == 0 && S == 0)break;
memset(vis,0,sizeof(vis));
int num = bfs();
if(num)printf("%d\n",num);
else printf("NO\n");
}
return 0;
}