HDU 2717 Catch That Cow

5 篇文章 0 订阅

原题链接:

http://acm.hdu.edu.cn/showproblem.php?pid=2717

题目大意:

输入一个N和K。表示你的起点是N。终点为K。每次有3中移动方式。
1.移动到X+1 的位置
2.移动到X-1的位置
3.移动到2X的位置
X为你当前的位置。问从N开始。最少走几步才能到K

思路:

这时一道简单的BFS水题。按一般做法来解决就可以了

代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>

int vis[100005];
int Pre[100005];
int N,K,number;
using namespace std;

void GetCount( int Index )
{
    while( Pre[ Index ] != -1 )
    {
        Index = Pre[ Index ];
        number++;
    }
}

bool IsLeagal( int Next )
{
    if( Next < 0 || Next >= 100005 )
        return false;
    return true;
}
void  bfs()
{
    queue<int> line;
    memset( Pre,0,sizeof(Pre));
    memset( vis,0,sizeof(Pre));
    vis[ N ] = true;
    Pre[ N ] = -1;
    line.push ( N );

    int Now,next_1,next_2,next_3;
    while( !line.empty ())
    {
        Now = line.front ();
        line.pop ();
        if( Now == K )
        {
            return ;
        }
        next_1 = Now +1;
        if( !vis[next_1] && IsLeagal(next_1) )
        {
            Pre[next_1] = Now;
            vis[next_1] = true;
            line.push ( next_1 );
        }

        next_2 = Now - 1;
        if( !vis[next_2] && IsLeagal(next_2) )
        {
            Pre[next_2] = Now;
            vis[next_2] = true;
            line.push ( next_2 );
        }

        next_3 = Now * 2;
        if( !vis[next_3] && IsLeagal(next_3))
        {
            Pre[next_3] = Now;
            vis[next_3] = true;
            line.push ( next_3 );
        }
    }
}
int main()
{
    while( cin >> N >> K)
    {
        number = 0;
        bfs();
        GetCount( K );
        cout<<number<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值