POJ_3278 Catch That Cow (bfs)

题目来源:点击打开链接


题目大意:John要去寻找他的cow,现在分别给出John的位置N和cow的位置k(他两处于同一行),John可以向左和向右移动,如果他的位置为X,则下一次他的位置可以为X-1、X+1、2*X,每移动一次需要1分钟,假设now不知道John想去找他,现在想问,John最少要花费多久才能到达cow的位置?


仔细想了想,这是一个简单的广搜问题,从John的位置开始搜索,分别向左右移动,直至他的位置与cow的重合。


代码:

#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>

using namespace std;
int n;//记录John所在的位置
int k;//记录从未所在的位置
//int ans;
const int maxn = 200000+5;
struct record{
    int pos;
    int cnt;
};
struct record que[maxn];
int visited[maxn];//记录John有没有走过某位置

void bfs()
{

     int head = 0;//队头
     int tail = 0;//队尾
     que[head].pos = n;//将John的初始位置入队
     que[head].cnt = 0;//初始移动位置为0
     tail++;//入队之后队尾+1
     visited[n] = 1;//标记第n已经走过

     int tx = n;
     while( head < tail)
     {
         for( int i = 0; i < 3; i++)
         {
            if( i == 0)
               tx = que[head].pos-1;//左移一位
            else if( i == 1)
               tx = que[head].pos+1;//右移一位
            else if( i == 2)
               tx = que[head].pos*2;//右移yx位

            if( tx < 0 || tx > maxn)//john的位置小于0,无意义
                continue;

            //如果没走过
            if( visited[tx] == 0)
            {
                visited[tx] = 1;//标记当前tx已经走过
                que[tail].pos = tx;//将当前位置入队
                que[tail].cnt = que[head].cnt+1;//走过的次数位head时的次数+1
                //printf("%d %d\n",que[tail].pos,que[tail].cnt);
                if( que[tail].pos == k)
                {
                    printf("%d\n",que[tail].cnt);
                        return;
                }
                tail++;
            }

         }
         head++;
     }

}

int main()
{
    while( scanf("%d%d",&n,&k) == 2)
    {
        if( n == k)
            printf("0\n");//不用走

        memset( visited,0,sizeof( visited));
       // ans = 0;
        bfs();
        //printf("%d\n",ans);

    }

    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值