(好好写结题报告)题意:给送三个杯子大小,前两个杯子可以进行六个操作,倒满,泼掉,一个杯子到另一个杯子。问最少步骤使前两个杯子存在的水是最后一个杯子的容量。
不假思索,这类从一个起点开始找满足某个条件下最优解,用广搜朝这个六个方向搜索,直到搜到。有两个难点,一个是搜索完后需要输出路径,目前只会比较熟练用回溯,用一个元素记载每一个状态上一个状态在数组的位置(所以这里用结构体数组做,而不是因为我不知道这个怎么回溯。。。)
还有一个难点就是。。。妈蛋这个情况有点多啊。。。模拟起来 有点考验我码力。。。当然 最后我还是ac一次~!
#include<cstdio>
#include<cstring>
#include<iostream>
#include<stack>
#include<algorithm>
#include<queue>
using namespace std;
struct Pot
{
int a;
int b;
int father;
int action;
int step;
Pot(){father=-1;}
}Q[100050];
stack<Pot>s;
int book[105][105],A,B,C;
void print(int i)
{
if(Q[i].father!=-1)
{
print(Q[i].father);
if(Q[i].action==1)
printf("FILL(1)\n");
if(Q[i].action==2)
printf("FILL(2)\n");
if(Q[i].action==3)
printf("DROP(1)\n");
if(Q[i].action==4)
printf("DROP(2)\n");
if(Q[i].action==5)
printf("POUR(1,2)\n");
if(Q[i].action==6)
printf("POUR(2,1)\n");
}
}
int bfs()
{
int head=0,tail=0;
memset(book,0,sizeof(book));
Pot s;s.a=0,s.b=0;
Q[tail].a=0;
Q[tail].b=0;
tail++;
book[0][0]=1;
while(head<tail)
{
Pot now,next;
now=next=Q[head];
for(int i=0;i<36;i++)
{
if(i==0&&now.a<A&&book[A][now.b]==0)
{
book[A][now.b]=1;
next.a=A;
next.b=now.b;
next.step=now.step+1;
next.father=head;
next.action=1;
Q[tail++]=next;
}
if(i==1&&now.b<B&&book[now.a][B]==0)
{
book[now.a][B]=1;
next.a=now.a;
next.b=B;
next.step=now.step+1;
next.father=head;
next.action=2;
Q[tail++]=next;
}
if(i==2&&now.a>0&&book[0][now.b]==0)
{
book[0][now.b]=1;
next.a=0;
next.b=now.b;
next.step=now.step+1;
next.father=head;
next.action=3;
Q[tail++]=next;
}
if(i==3&&now.b>0&&book[now.a][0]==0)
{
book[now.a][0]=1;
next.a=now.a;
next.b=0;
next.step=now.step+1;
next.father=head;
next.action=4;
Q[tail++]=next;
}
if(i==4&&now.a>0&&now.b<B)
{
if(now.a+now.b<=B&&book[0][now.a+now.b]==0)
{
book[0][now.a+now.b]=1;
next.a=0;
next.b=now.a+now.b;
next.step=now.step+1;
next.father=head;
next.action=5;
Q[tail++]=next;
}
else if(now.a+now.b>B&&book[now.a-B+now.b][B]==0)
{
book[now.a-B+now.b][B]=1;
next.a=now.a+now.b-B;
next.b=B;
next.step=now.step+1;
next.father=head;
next.action=5;
Q[tail++]=next;
}
else
continue;
}
if(i==5&&now.a<A&&now.b>0)
{
if(now.b+now.a<=A&&book[now.a+now.b][0]==0)
{
book[now.a+now.b][0]=1;
next.a=now.a+now.b;
next.b=0;
next.step=next.step+1;
next.father=head;
next.action=6;
Q[tail++]=next;
}
else if(now.a+now.b>A&&book[A][now.b-A+now.a]==0)
{
book[A][now.a+now.b-A]=1;
next.a=A;
next.b=now.a+now.b-A;
next.step=now.step+1;
next.father=head;
next.action=6;
Q[tail++]=next;
}
else
continue;
}
if(next.a==C||next.b==C)
{
printf("%d\n",Q[tail-1].step);
print(tail-1);
return 1;
}
}
head++;
}
return 0;
}
int main()
{
while(~scanf("%d %d %d",&A,&B,&C))
{
int flag=bfs();
if(flag==0)
printf("impossible\n");
}
}