zoukankan      html  css  js  c++  java
  • 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
    ",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
    ");
        }
        return 0;
    }
  • 相关阅读:
    笔记2-斐波那契数列
    笔记1-排序
    C++ 顶层const和底层const ?
    C++指针常量与常量指针的区别?
    C++指针和引用的区别?
    函数指针, 指针函数?
    手机横竖屏问题
    Swift
    Swift 渐变色
    Swift guard 关键字
  • 原文地址:https://www.cnblogs.com/zhanglichen/p/12311123.html
Copyright © 2011-2022 走看看