POJ

来源:互联网 发布:gta5线上ae86改装数据 编辑:程序博客网 时间:2024/06/05 18:34

题目大意:有编号 1、2 两个水壶,容量分别是 A、B,有 FILL、DROP、POUR 三种操作,现在要通过这些操作得到 C 升水,问最少几步,并输出步骤。
FILL(i) 装满水壶 i
DROP(i) 倒空水壶 i
POUR(i, j) i 向 j 倒水,若 j 满了,则多余的水留在 i 中
解题思路:因为 i,j 都可以取 1、2,所以仔细拆分一下其实有 6 种操作,所以是 6 个入口的 BFS。
一开始用 STL 的 queue 做,发现路径没法输出了,就换成数组,把所有操作都保留下来。结构体 point 里 t 表示操作,pre 表示前一个状态的坐标,cnt 统计操作次数。输出的时候用递归,从最终状态的 pre 一直往前找到原始状态,然后再开始输出操作。

#include<iostream>#include<stdio.h>#include<algorithm>#include<cmath>#include<string>#include<string.h>#include<queue>#include<map>#define max(a,b) ((a)>(b)?(a):(b))#define min(a,b) ((a)<(b)?(a):(b))const int INF = 0x3f3f3f3f;const int NINF = -INF -1;const int MAXN = 100+10;using namespace std;int A, B, C;struct point {    int a, b;    int t, pre, cnt;}q[MAXN*MAXN];int ans, bg;bool flag, vis[MAXN][MAXN];void bfs() {    int t1, t2;    t1 = t2 = 0;    q[t2].a = q[t2].b = q[t2].t = q[t2].pre = q[t2].cnt = 0;    t2++;    point now, p;    while (t1 < t2) {        now = q[t1++];        if (now.a == C || now.b == C) {            bg = t1-1;            ans = now.cnt;            flag = 1;            break;        }        for (int i = 0; i < 6; i++) {            p = now;            p.t = i;            p.cnt = now.cnt+1;            if (i == 0) { //fill(1)                p.a = A;            }            if (i == 1) { //fill(2)                p.b = B;            }            if (i == 2) { //drop(1)                p.a = 0;            }            if (i == 3) { //drop(2)                p.b = 0;            }            if (i == 4) { //pour(1,2)                p.b += p.a;                if (p.b <= B) p.a = 0;                if (p.b > B) {                    p.a = p.b - B;                    p.b = B;                }            }            if (i == 5) { //pour(2,1)                p. a += p.b;                if (p.a <= A) p.b = 0;                if (p.a > A) {                    p.b = p.a - A;                    p.a = A;                }            }            if (!vis[p.a][p.b]) {                vis[p.a][p.b] = true;                p.pre = t1-1;                q[t2++] = p;            }        }    }}void print_ans(int i) {    if (i == 0) return;    print_ans(q[i].pre);    if (q[i].t == 0) printf("FILL(1)");    if (q[i].t == 1) printf("FILL(2)");    if (q[i].t == 2) printf("DROP(1)");    if (q[i].t == 3) printf("DROP(2)");    if (q[i].t == 4) printf("POUR(1,2)");    if (q[i].t == 5) printf("POUR(2,1)");    printf("\n");}int main() {    while (scanf("%d%d%d", &A, &B, &C) != EOF) {        ans = 0;        flag = 0;        memset(vis, 0, sizeof(vis));        bfs();        if (flag) {            printf("%d\n", ans);            print_ans(bg);        }        else printf("impossible\n");    }    return 0;}
原创粉丝点击