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

BFS [NYOJ 21] 三个水杯

时间:2014-11-01 16:08:33      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   for   sp   数据   div   

三个水杯

时间限制: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

水BFS、上代码 - -
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
#define N 110

struct Water
{
    int w[3],t;
};

int v[3],e[3];
int vis[N][N][N];

void pour(Water &t,int i,int j) //i往j倒水
{
    if(v[j]-t.w[j]>=t.w[i])
    {
        t.w[j]+=t.w[i];
        t.w[i]=0;
    }
    else 
    {
        t.w[i]-=v[j]-t.w[j];
        t.w[j]=v[j];
    }
}
void BFS()
{
    queue<Water> q;
    memset(vis,0,sizeof(vis));
    Water now,next;
    now.w[0]=v[0];
    now.w[1]=0;
    now.w[2]=0;
    now.t=0;
    q.push(now);
    vis[v[0]][0][0]=1;
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        if(now.w[0]==e[0] && now.w[1]==e[1] && now.w[2]==e[2])
        {
            cout<<now.t<<endl;
            return;
        }
        for(int i=0;i<3;i++)
        {
            for(int j=0;j<3;j++)
            {
                if(i==j) continue;
                next=now;
                pour(next,i,j);
                if(!vis[next.w[0]][next.w[1]][next.w[2]])
                {
                    next.t++;
                    q.push(next);
                    vis[next.w[0]][next.w[1]][next.w[2]]=1;
                }
            }
        }
    }
    cout<<-1<<endl;
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d%d",&v[0],&v[1],&v[2]);
        scanf("%d%d%d",&e[0],&e[1],&e[2]);
        BFS();
    }
    return 0;
}

 

BFS [NYOJ 21] 三个水杯

标签:style   blog   io   color   os   for   sp   数据   div   

原文地址:http://www.cnblogs.com/hate13/p/4067173.html

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