FZU--2188(搜索+剪枝)

F - 过河I
Time Limit:3000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

Description

一天,小明需要把x只羊和y只狼运输到河对面。船可以容纳n只动物和小明。每次小明划船时,都必须至少有一只动物来陪他,不然他会感到厌倦,不安。不论是船上还是岸上,狼的数量如果超过羊,狼就会把羊吃掉。小明需要把所有动物送到对面,且没有羊被吃掉,最少需要多少次他才可以穿过这条河?

Input

有多组数据,每组第一行输入3个整数想x, y, n (0≤ x, y,n ≤ 200)

Output

如果可以把所有动物都送过河,且没有羊死亡,则输出一个整数:最少的次数。 否则输出 -1 .

Sample Input

3 3 233 33 3

Sample Output

11-1

Hint

第一个样例

次数 船 方向 左岸 右岸(狼 羊)

0: 0 0 3 3 0 0

1: 2 0 > 1 3 2 0

2: 1 0 < 2 3 1 0

3: 2 0 > 0 3 3 0

4: 1 0 < 1 3 2 0

5: 0 2 > 1 1 2 2

6: 1 1 < 2 2 1 1

7: 0 2 > 2 0 1 3

8: 1 0 < 3 0 0 3

9: 2 0 > 1 0 2 3

10: 1 0 < 2 0 1 3

11: 2 0 > 0 0 3 3


乍一看以为是dp,其实看数据范围是一道bfs搜索,里面有各种简单的剪枝,vis[i][j][d]表示船上有i只羊,j只狼,d表示船的方向,0表示开始,1表示对岸。

代码:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<string>
#include<cmath>
#include<queue>
#include<vector>
#include<map>
#include<set>
#define INF 0x3f3f3f3f
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int maxd=200+5;

#define lson l,m,rt<<1
#define rson m+1,r,rt<<1 | 1
typedef long long ll;
typedef pair<int,int> pii;
//---------------------------
int dx[]= {0,0,1,-1};
int dy[]= {1,-1,0,0};
typedef struct node
{
    int x,y,d,t;
    node(int x_ = 0, int y_ = 0,int d_=0, int t_ = 0)
    {
        x = x_;
        y = y_;
        d = d_;
        t = t_;
    }
};
int vis[maxd][maxd][3];
int x,y,n;

int bfs(int a,int b,int d,int t)
{
    queue<node> q;
    node tmp(a,b,d,t);
    q.push(tmp);
    vis[tmp.x][tmp.y][0]=1;
    while(!q.empty())
    {
        node now=q.front();
        q.pop();
        if(now.x==x && now.y==y && now.d==1)
        {
            return now.t;
        }

        for(int i=0; i<=now.x; ++i) ///sheep
            for(int j=0; j<=now.y; ++j) ///wolf
            {
                if(i+j==0 ) continue;
                if((i<j) && i) continue;
                if(i+j>n) continue;

                if((now.x-i<now.y-j) && (now.x-i)) continue;
                if((x-now.x+i < y-now.y+j) && (x-now.x+i)) continue;
                if(vis[x-now.x+i][y-now.y+j][!now.d]) continue;
                node tmp(x-now.x+i,y-now.y+j,!now.d,now.t+1);
                q.push(tmp);
                vis[tmp.x][tmp.y][tmp.d]=1;
            }
    }
    return -1;
}


int main()
{
    freopen("1.txt","r",stdin);
    while( scanf("%d%d%d",&x,&y,&n)!=EOF)
    {
         mem(vis,0);
        int ans=bfs(x,y,0,0);
        printf("%d\n",ans);
    }
    return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值