此题为经典的BFS问题。
为了让代码简洁一点,我牺牲了效率——话说我不知道效率具体牺牲在哪里了==!
/*
* hdu-1495 非常可乐
* mike-w
* 2012-3-16
*********************
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_SIZE 120
#define Q_SIZE 10000
int N,M,S,half;
int rec[MAX_SIZE][MAX_SIZE][MAX_SIZE];
int cap[3];
int trans[6][2]={0,1,0,2,1,0,1,2,2,0,2,1};
int que[Q_SIZE][3],qhead,qtail,qlen;
int enque(int e1, int e2, int e3)
{
if(qlen==Q_SIZE)
return -1;
qlen++;
que[qtail][0]=e1;
que[qtail][1]=e2;
que[qtail][2]=e3;
qtail=++qtail%Q_SIZE;
return 0;
}
int deque(int *e1, int *e2 ,int *e3)
{
if(qlen==0)
return -1;
qlen--;
*e1=que[qhead][0];
*e2=que[qhead][1];
*e3=que[qhead][2];
qhead=++qhead%Q_SIZE;
return 0;
}
int search(void)
{
int i,j,from,to;
int f[3],ff[3];
qhead=qtail=qlen=0;
enque(S,0,0);
rec[S][0][0]=1;
while(deque(f,f+1,f+2)!=-1)
{
if(f[0]==half && half==f[1]
|| f[0]==half && half==f[2]
|| f[1]==half && half==f[2])
return rec[f[0]][f[1]][f[2]]-1;
for(i=0;i<6;i++)
{
for(j=0;j<3;j++)
ff[j]=f[j];
from=trans[i][0];
to=trans[i][1];
ff[to]+=ff[from];
ff[from]=0;
if(ff[to]>cap[to])
ff[from]=ff[to]-cap[to],ff[to]=cap[to];
if(!rec[ff[0]][ff[1]][ff[2]])
{
enque(ff[0], ff[1], ff[2]);
rec[ff[0]][ff[1]][ff[2]]=rec[f[0]][f[1]][f[2]]+1;
}
}
}
return -1;
}
int main(void)
{
#ifndef ONLINE_JUDGE
freopen("in","r",stdin);
#endif
int ans;
while(scanf("%d%d%d",&S,&N,&M)!=EOF,S)
{
if(S&0x1)
{
puts("NO");
continue;
}
memset(rec,0,sizeof(rec));
cap[0]=S;
cap[1]=N;
cap[2]=M;
half=S/2;
ans=search();
if(ans>0)
printf("%d\n",ans);
else
puts("NO");
}
return 0;
}