POJ 3278 Catch That Cow

题目描述:

农夫FJ要经过一定的步数走到他的牛所在的位置,农夫和牛在一条直线上,农夫在点N的位置,他的牛在点K的位置。

农夫没走一步有三种走法,假设农夫现在的位置在x,

三种走法为:1、FJ一步走到x-1的位置

2、FJ一步走到x+1的位置

3、FJ一步走到x*2的位置

要求输出FJ走到牛所在位置所用的最小步数

代码如下:

#include<stdio.h>
#include<string.h>
#define Max 300000
int res;
int mark[Max];  //用于标记第i个点是否已经走过,
struct Pos{     //每次走的位置信息
    int x;      //点x
    int step;   //走到点x这个位置时用的最小的步数
};
Pos pos[Max];
void bfs(int n,int k){
    int tmp;
    int pre=0,last=0;
    res=0;
    pos[0].x=n;pos[0].step=0;
    mark[n]=1;
    while(pre<=last){
        tmp=pos[pre].x-1;
        if(tmp>=0 && tmp<=Max && mark[tmp]==0){  //剪枝
            mark[tmp]=1;
            pos[++last].x=tmp;
            pos[last].step=pos[pre].step+1;
            if(pos[last].x==k){
                res=pos[last].step;
                return ;
            }
        }
        tmp=pos[pre].x+1;
        if(tmp>=0 && tmp<=Max && mark[tmp]==0){  //剪枝
            mark[tmp]=1;
            pos[++last].x=tmp;
            pos[last].step=pos[pre].step+1;
            if(pos[last].x==k){
                res=pos[last].step;
                return ;
            }
        }
        tmp=pos[pre].x*2;
        if(tmp>=0 && tmp<=Max && mark[tmp]==0){   //剪枝
            mark[tmp]=1;
            pos[++last].x=tmp;
            pos[last].step=pos[pre].step+1;
            if(pos[last].x==k){
                res=pos[last].step;
                return ;
            }
        }
        pre++;
    }
}
int main(){
    int n,k;
    while(~scanf("%d%d",&n,&k)){
        memset(mark,0,sizeof(mark));
        bfs(n,k);
        printf("%d\n",res);
    }
    return 0;
}

本题的主要思路就是宽度优先搜索加剪枝,使用结构体记录没走到一步的位置x和走到这个位置所用的步数step,通过剪枝可以将入栈的数据缩小到Max大小,否则数据量会非常大,导致提交题目后出现RE,因为在mark标记的时候会出现下标小于0。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值