zoukankan      html  css  js  c++  java
  • nyoj 21 三个水杯 BFS

    三个水杯

    时间限制:1000 ms  |  内存限制:65535 KB
    难度:4
    描述
    给出三个水杯,大小不一,并且只有最大的水杯的水是装满的,其余两个为空杯子。三个水杯之间相互倒水,并且水杯没有标识,只能根据给出的水杯体积来计算。现在要求你写出一个程序,使其输出使初始状态到达目标状态的最少次数。
    输入
    第一行一个整数N(0<N<50)表示N组测试数据
    接下来每组测试数据有两行,第一行给出三个整数V1 V2 V3 (V1>V2>V3 V1<100 V3>0)表示三个水杯的体积。
    第二行给出三个整数E1 E2 E3 (体积小于等于相应水杯体积)表示我们需要的最终状态
    输出
    每行输出相应测试数据最少的倒水次数。如果达不到目标状态输出-1
    样例输入
    2
    6 3 1
    4 1 1
    9 3 2
    7 1 1
    样例输出
    3
    -1
    View Code
    #include<stdio.h>
    #include<queue>
    #include<string.h>
    using namespace std;
    struct node
    {
        int c[3];
        int move[3]; 
        int step;
    };
    int visit[1010100];
    
    int  hash(node a)
    {
    return (a.move[1]*10000+a.move[1]*100+a.move[2]*10);
    }
    
    int judge(node a,node b)
    {
        return (a.move[0]==b.move[0]&&a.move[1]==b.move[1]&&a.move[2]==b.move[2]);
    }
    
    int main()
    {
        int x,i,j,min,ok;
        node begin,end;
        queue<node>s;
        scanf("%d",&x);
        while(x--)
        {
            scanf("%d%d%d",&begin.c[0],&begin.c[1],&begin.c[2]);
            begin.move[0]=begin.c[0];
            begin.move[1]=begin.move[2]=0;
            begin.step=0;
            s.push(begin);
            scanf("%d%d%d",&end.move[0],&end.move[1],&end.move[2]); //后面是判定move数组
            ok=0;
            memset(visit,0,sizeof(visit));
            visit[hash(begin)]=1;
            while(!s.empty())
            {
                node u=s.front();
                s.pop();
                if(judge(u,end))
                {
                    printf("%d\n",u.step);
                    ok=1;
                    break;
                }
                for(i=0;i<3;i++)//从i倒到j
                    for(j=0;j<3;j++)
                        if(i!=j)
                        {
                            min=u.c[j]-u.move[j];
                            if(u.move[i]<min)
                                min=u.move[i];
                            node v=u;
                            v.move[i]-=min;
                            v.move[j]+=min;
                            v.step++;
                            if(!visit[hash(v)])
                            {
                                visit[hash(v)]=1;
                                s.push(v);
                            }
                        }
            }
            if(!ok)
                printf("-1\n");
            while(!s.empty())
                s.pop();
        }
        return 0;
    }

    本题主要是用BFS搜索各种情况,用队列存贮状态,直到搜到所要答案。以后这种情况很多的类型,相互变换的都可以用BFS尝试下

  • 相关阅读:
    115今天太给力了~
    使用jQuery顺序显示元素
    温习浏览器渲染模式
    去除浏览器a标签链接时,烦人的虚线框
    设计可以是一种垄断
    如何获取鼠标选中的文字
    积极参与到FuckIE6的队伍中...
    google今儿发现页面又变好看了
    20101207google 今天出新功能了
    火狐ff下margintop太给力
  • 原文地址:https://www.cnblogs.com/zibuyu/p/2957290.html
Copyright © 2011-2022 走看看