题意:有二个水壶,对水壶有三种操作,1)FILL(i),将i水壶的水填满,2)DROP(i),将水壶i中的水全部倒掉,3)POUR(i,j)将水壶i中的水倒到水壶j中,若水壶 j 满了,则 i 剩下的就不倒了,问进行多少步操作,并且怎么操作,输出操作的步骤,两个水壶中的水可以达到C这个水量。如果不可能则输出impossible。初始时两个水壶是空的,没有水。
简单题目,纯属练习。。。跟这个类似的------>>>点击打开链接
#include<stdio.h>
#include<string.h>
int a,b,p;
struct node
{
int a,b,step;
int pre,flag;
} q[1000],t,f;
int s[101][101];
void shuchu(int qian)
{
int a[101];
int k=0;
for(int i=qian; i!=-1; i=q[i].pre)
{
a[k++]=q[i].flag;
}
for(int i=k-1;i>=0;i--)
{
if(a[i]==1)
printf("FILL(1)\n");
else if(a[i]==2)
printf("FILL(2)\n");
else if(a[i]==3)
printf("DROP(1)\n");
else if(a[i]==4)
printf("DROP(2)\n");
else if(a[i]==5)
printf("POUR(1,2)\n");
else if(a[i]==6)
printf("POUR(2,1)\n");
}
}
int bfs()
{
int i;
int qian=1;
int hou=0;
q[0].a=0;
q[0].b=0;
q[0].flag=-1;
q[0].pre=-1;
q[0].step=0;
s[0][0]=1;
while(qian>hou)
{
t=q[hou++];
if(t.a==p||t.b==p)
{
printf("%d\n",t.step);
shuchu(hou-1);
return 0;
}
f.a=a;
f.b=t.b;
if(s[f.a][f.b]==0)
{
f.flag=1;
f.pre=hou-1;
f.step=t.step+1;
q[qian++]=f;
s[f.a][f.b]=1;
}
f.a=t.a;
f.b=b;
if(s[f.a][f.b]==0)
{
f.flag=2;
f.pre=hou-1;
f.step=t.step+1;
q[qian++]=f;
s[f.a][f.b]=1;
}
f.a=0;
f.b=t.b;
if(s[f.a][f.b]==0)
{
f.flag=3;
f.pre=hou-1;
f.step=t.step+1;
q[qian++]=f;
s[f.a][f.b]=1;
}
f.a=t.a;
f.b=0;
if(s[f.a][f.b]==0)
{
f.flag=4;
f.pre=hou-1;
f.step=t.step+1;
q[qian++]=f;
s[f.a][f.b]=1;
}
f.b=t.b+t.a;
f.a=t.a-(b-t.b);
if(f.b>=b)
f.b=b;
if(f.a<0)
f.a=0;
if(s[f.a][f.b]==0)
{
f.flag=5;
f.pre=hou-1;
f.step=t.step+1;
q[qian++]=f;
s[f.a][f.b]=1;
}
f.a=t.a+t.b;
f.b=t.b-(a-t.a);
if(f.a>=a)
f.a=a;
if(f.b<0)
f.b=0;
if(s[f.a][f.b]==0)
{
f.flag=6;
f.pre=hou-1;
f.step=t.step+1;
q[qian++]=f;
s[f.a][f.b]=1;
}
}
printf("impossible\n");
return 0;
}
int main()
{
while(scanf("%d %d %d",&a,&b,&p)!=EOF)
{
memset(s,0,sizeof(s));
bfs();
}
return 0;
}