题意:
倒水问题。给三个数a,b,x,a、b为两个罐子的容积,输出几步可以倒出x。
分析:
额,又是BFS。
#include <cstdio>
#include <cstring>
#define MAX 101
#define FILL 0
#define POUR 1
#define DROP 2
using namespace std;
struct Node{
int v[2];
int fa, dist, path;
};
int a, b, x;
char vis[MAX][MAX];
char str[][10]={"FILL(1)", "FILL(2)", "DROP(1)", "DROP(2)", "POUR(1,2)", "POUR(2,1)"};
Node q[MAX*MAX];
void printPath(int n)
{
if(n != q[n].fa)
printPath(q[n].fa);
if(n!=0)
printf("%s\n", str[q[n].path]);
}
void bfs()
{
int front=0, rear=1;
q[0].v[0] = q[0].v[1] = q[0].fa = 0;
vis[0][0] = 1;
while(front < rear)
{
Node& u = q[front];
if(u.v[0] == x || u.v[1] == x)
{
printf("%d\n", q[front].dist);
printPath(front);
return;
}
int t;
for(int i=0; i < 6; ++i)
{
Node& v = q[rear];
for(int i=0; i < 2; ++i)
v.v[i] = u.v[i];
switch(i){
case 0: //Fill A
v.v[0] = a;
break;
case 1: //Fill B
v.v[1] = b;
break;
case 2: //Drop A
v.v[0] = 0;
break;
case 3: //Drop B
v.v[1] = 0;
break;
case 4: //Pour from A to B
t = v.v[0] > (b-v.v[1]) ? (b-v.v[1]) : v.v[0];
v.v[0] -= t;
v.v[1] += t;
break;
case 5: //Pout from B to A
t = v.v[1] > (a-v.v[0]) ? (a-v.v[0]) : v.v[1];
v.v[0] += t;
v.v[1] -= t;
break;
}
if(!vis[v.v[0]][v.v[1]])
{
v.fa = front;
vis[v.v[0]][v.v[1]] = 1;
v.dist = q[front].dist + 1;
++rear;
v.path = i;
}
}
++front;
}
printf("impossible\n");
}
int main()
{
while(scanf("%d%d%d", &a, &b, &x) == 3)
{
memset(vis, 0, sizeof(char)*MAX*MAX);
bfs();
}
return 0;
}