ZOJ1005 Jugs

题意:有两个容量互质的容器,需要用这两个容器量出目标重量的水,找到其中一组解。
bfs,使得搜索得到的解是步数最少的,遍历前驱法输出路径~
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+14;
struct node {
    int a,b;
    int pre;
    int flag;
}Node[maxn];
int last;
int p;
int ca,cb,n;
char s[6][15] = {"fill A","fill B","empty A","empty B","pour A B","pour B A"};
unordered_map<int,int> pos;
void dfs (int x) {
    if (Node[x].pre==-1) return;
    dfs (Node[x].pre);
    printf ("%s\n",s[Node[x].flag]);
}
void bfs (int a,int b) {
    if (p>last) return;
    if (a==n||b==n) return;
    if (pos[a]!=b+1) {
        pos[a]=b+1;
        if (a<ca) {
            Node[++last].a=ca;
            Node[last].b=b;
            Node[last].flag=0;
            Node[last].pre=p;
        }
        if (b<cb) {
            Node[++last].a=a;
            Node[last].b=cb;
            Node[last].flag=1;
            Node[last].pre=p;
        }
        if (a!=0) {
            Node[++last].a=a;
            Node[last].b=b;
            Node[last].flag=2;
            Node[last].pre=p;
        }
        if (b!=0) {
            Node[++last].a=a;
            Node[last].b=0;
            Node[last].flag=3;
            Node[last].pre=p;
        }
        if (a!=0&&b<cb) {
            Node[++last].a=max(0,a+b-cb);
            Node[last].b=a+b-Node[last].a;
            Node[last].flag=4;
            Node[last].pre=p;
        } 
        if (b!=0&&a<ca) {
            Node[++last].b=max(0,a+b-ca);
            Node[last].a=a+b-Node[last].b;
            Node[last].flag=5;
            Node[last].pre=p;
        }
    }
    p++;
    bfs(Node[p].a,Node[p].b);
}
int main () {
    Node[0].pre=-1;
    while (~scanf("%d %d %d",&ca,&cb,&n)) {
        p=0;
        last=0;
        pos.clear();
        bfs(0,0);
        dfs(p);
        printf ("success\n");
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zhanglichen/p/12311123.html
ZOJ
今日推荐