码迷,mamicode.com
首页 > 其他好文 > 详细

ZOJ1005 Jugs

时间:2020-02-15 13:24:31      阅读:40      评论:0      收藏:0      [点我收藏+]

标签:printf   str   搜索   return   dfs   ret   div   amp   bfs   

题意:有两个容量互质的容器,需要用这两个容器量出目标重量的水,找到其中一组解。
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;
}

 

ZOJ1005 Jugs

标签:printf   str   搜索   return   dfs   ret   div   amp   bfs   

原文地址:https://www.cnblogs.com/zhanglichen/p/12311123.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!