POJ 1606 Jugs(BFS:找最短路径并输出)

POJ 1606 Jugs(BFS:找最短路径并输出)

http://poj.org/problem?id=1606

题意:

        又是给你两个容量为A和B的水杯,要你倒出B杯子有C升水的路径.

分析:

本题之前我就做过一道类似的的:

http://blog.csdn.net/u013480600/article/details/25241777

上面有分析.下面直接给出代码:

AC代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;
const int maxr=100+5;
const int maxc=100+5;
const int maxn=10000+100;//这个规模是测试OJ得出的
int A,B,C;
int vis[maxr][maxc],dist[maxr][maxc],pre[maxr][maxc];
struct Cell
{
    int a,b;
    Cell(int a,int b):a(a),b(b){}
};

int cnt;
struct Node
{
    int a,b;
    int t;
    Node(){}
    Node(int a,int b,int t):a(a),b(b),t(t){}
}nodes[maxn];

Cell BFS()
{
    queue<Cell> Q;
    Q.push(Cell(0,0));
    memset(vis,0,sizeof(vis));
    vis[0][0]=1;
    dist[0][0]=0;
    cnt=0;
    while(!Q.empty())
    {
        Cell cell=Q.front();Q.pop();
        int a=cell.a,b=cell.b;
        for(int d=0;d<6;d++)
        {
            int na,nb;
            if(d==0){na=A,nb=b;}
            else if(d==1) {na=a,nb=B;}
            else if(d==2) {na=0,nb=b;}
            else if(d==3) {na=a,nb=0;}
            else if(d==4)
            {
                int all=a+b;
                na= all>=B?all-B:0;
                nb= all>=B? B:all;
            }
            else if(d==5)
            {
                int all=a+b;
                na= all>=A? A:all;
                nb= all>=A? all-A:0;
            }
            if(vis[na][nb]==0)
            {
                vis[na][nb]=1;
                dist[na][nb]=dist[a][b]+1;
                nodes[cnt++]=Node(a,b,d);
                pre[na][nb]=cnt-1;
                Q.push(Cell(na,nb));
                if(nb==C) return Cell(na,nb);
            }
        }
    }
    return Cell(-1,-1);
}
int main()
{
    while(scanf("%d%d%d",&A,&B,&C)==3)
    {
        Cell cell=BFS();
        stack<int> S;
        int a=cell.a ,b=cell.b;
        while(true)
        {
            int tmp=pre[a][b];
            S.push(nodes[tmp].t);
            a=nodes[tmp].a,b=nodes[tmp].b;
            if(a==0&&b==0) break;
        }
        while(!S.empty())
        {
            int t=S.top();S.pop();
            if(t==0) printf("fill A\n");
            else if(t==1) printf("fill B\n");
            else if(t==2) printf("empty A\n");
            else if(t==3) printf("empty B\n");
            else if(t==4) printf("pour A B\n");
            else if(t==5) printf("pour B A\n");
        }
        printf("success\n");
    }
    return 0;
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值