【BFS】FZOJ 过河I 2188

来源:互联网 发布:淘宝网店发布宝贝教程 编辑:程序博客网 时间:2024/04/28 02:06

Problem 2188 过河I

Accept: 104    Submit: 259
Time Limit: 3000 mSec    Memory Limit : 32768 KB

Problem 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

Source

FOJ有奖月赛-2015年03月

Submit  Back  Status  Discuss

解题思路:

可以用BFS遍历每一种可能。

AC代码:

#include <stdio.h>#include <string.h>#include <queue>#include <algorithm>using namespace std;struct P{    int x,y;    int d,s;};const int MAXN = 201;int X,Y,N;bool used[2][MAXN][MAXN];int BFS(){    P T,E;    queue<P> Q;    T.x=X;T.y=Y;T.d=0;T.s=0;    Q.push(T);    used[0][X][Y]=1;    while(!Q.empty()){        T=Q.front();        Q.pop();        if(T.d==1&&T.x==X&&T.y==Y){            return T.s;        }        int sx=X-T.x,sy=Y-T.y;        for(int i=0;i<=T.x;i++){            for(int j=0;j<=T.y;j++){                if((i>=j||i==0)&&(i+j>0&&i+j<=N)&&(sx+i>=sy+j||sx+i==0)&&(T.x-i>=T.y-j||T.x-i==0)&&!used[1-T.d][sx+i][sy+j]){                    E.d=1-T.d;E.x=sx+i;E.y=sy+j;E.s=T.s+1;                    Q.push(E);                    used[E.d][E.x][E.y]=1;                }            }        }    }    return -1;}int main(){    while(scanf("%d%d%d",&X,&Y,&N)!=EOF){        memset(used,0,sizeof(used));        int num=BFS();        if(num==-1)printf("-1\n");        else printf("%d\n",num);    }    return 0;}

以N为循环条件~

#include <stdio.h>#include <string.h>#include <queue>#include <algorithm>using namespace std;struct P{    int x,y;    int d,s;};const int MAXN = 201;int X,Y,N;bool used[2][MAXN][MAXN];int BFS(){    P T,E;    queue<P> Q;    T.x=X;T.y=Y;T.d=0;T.s=0;    Q.push(T);    used[0][X][Y]=1;    while(!Q.empty()){        T=Q.front();        Q.pop();        if(T.d==1&&T.x==X&&T.y==Y){            return T.s;        }        int sx=X-T.x,sy=Y-T.y;        for(int i=0;i<=N;i++){            for(int j=0;j<=N-i;j++){                if((i>=j||i==0)&&i+j>0&&(i<=T.x&&j<=T.y)&&(sx+i>=sy+j||sx+i==0)&&(T.x-i>=T.y-j||T.x-i==0)&&!used[1-T.d][sx+i][sy+j]){                    E.d=1-T.d;E.x=sx+i;E.y=sy+j;E.s=T.s+1;                    Q.push(E);                    used[E.d][E.x][E.y]=1;                }            }        }    }    return -1;}int main(){    while(scanf("%d%d%d",&X,&Y,&N)!=EOF){        memset(used,0,sizeof(used));        int num=BFS();        if(num==-1)printf("-1\n");        else printf("%d\n",num);    }    return 0;}


0 0
原创粉丝点击