题目连接:http://acm.pku.edu.cn/JudgeOnline/problem?id=3414
1,广搜解决,可能是题目条件的特殊性或者是测试数据的局限性,我的广搜代码是有问题的,但是过了!入队就设标志位不能推迟到出队。
2,这个题目要保存节点的状态、步数、父节点广搜能保存的信息都保存了,由于队列足够大每个节点的信息都在队列中能找到,所以只要设置一个数组保存队列中父节点的下标即可。
#include <iostream>
using namespace std;
#define MAX 10000
struct Node
{
int a;
int b;
int step;
int flag;
int pre;
};
Node q[MAX];
int hd,tl;
bool visit[101][101];
int A,B,C;
int step[MAX];
void BFS()
{
Node cur,next;
cur.a = 0;
cur.b = 0;
cur.step = 0;
cur.pre = -1;
hd = tl = 0;
q[tl] = cur;
++tl;
int i,len;
memset(visit,0,sizeof(visit));
while(hd != tl)
{
cur = q[hd];
++hd;
visit[cur.a][cur.b] = true;
for(i = 0;i < 6;++i)
{
switch(i)
{
case 0:
next.a = A;
next.b = cur.b;
next.flag = 0;
break;
case 1:
next.a = cur.a;
next.b = B;
next.flag = 1;
break;
case 2:
next.a = 0;
next.b = cur.b;
next.flag = 2;
break;
case 3:
next.a = cur.a;
next.b = 0;
next.flag = 3;
break;
case 4:
if(B - cur.b < cur.a)
{
next.a = cur.a + cur.b - B;
next.b = B;
next.flag = 4;
}
else
{
next.a = 0;
next.b = cur.a + cur.b;
next.flag = 4;
}
break;
default:
if(A - cur.a < cur.b)
{
next.a = A;
next.b = cur.b + cur.a - A;
next.flag = 5;
}
else
{
next.a = cur.a + cur.b;
next.b = 0;
next.flag = 5;
}
}
if(!visit[next.a][next.b])
{
next.step = cur.step + 1;
next.pre = hd-1;
q[tl] = next;
++tl;
if(next.a == C || next.b == C)
break;
}
}
if(next.a == C || next.b == C)
{
i = tl-1;
len = 0;
while(q[i].pre != -1)
{
step[len] = i;
++len;
i = q[i].pre;
}
break;
}
}
if(tl == hd)
cout << "impossible" << endl;
else
{
cout << q[tl-1].step << endl;
for(i = len-1;i >= 0;--i)
{
switch(q[step[i]].flag)
{
case 0:
cout << "FILL(1)" << endl;
break;
case 1:
cout << "FILL(2)" << endl;
break;
case 2:
cout << "DROP(1)" << endl;
break;
case 3:
cout << "DROP(2)" << endl;
break;
case 4:
cout << "POUR(1,2)" << endl;
break;
default:
cout << "POUR(2,1)" << endl;
}
}
}
}
int main()
{
while(cin >> A >> B >> C)
{
BFS();
}
return 0;
}