POJ 3414 Pots

来源:互联网 发布:办公室必备软件 编辑:程序博客网 时间:2024/05/16 23:54

题意:

倒水问题。给三个数a,b,x,a、b为两个罐子的容积,输出几步可以倒出x。

分析:

额,又是BFS。

#include <cstdio>#include <cstring>#define MAX101#define FILL0#define POUR1#define DROP2using 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 Av.v[0] = a;break;case 1://Fill Bv.v[1] = b;break;case 2://Drop Av.v[0] = 0;break;case 3://Drop Bv.v[1] = 0;break;case 4://Pour from A to Bt = 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 At = 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;}


原创粉丝点击