2717:Catch That Cow

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2717

方法:bfs

思路:由于搜索空间还是很大的,如果用bfs的话很容易就会造成递归堆栈溢出,而且时间复杂度也会很高,所以采用bfs。这是我第一次手写bfs,借鉴了一下网上高手的经验,在此谢过。原理都是不难,只需要按照bfs的步骤一步步来就可以了。由于这里需要记录两个数据,因此会用到结构体,这样的话直接用STL里的queue会省很多事儿。

难点:queue的使用

参考链接:

本题 :http://blog.csdn.net/libin56842/article/details/9017449

queue: http://blog.csdn.net/morewindows/article/details/6950917

#include<iostream>
#include<climits>
#include<queue>
#include<cstring>
using namespace std;
int n,k;
const int N = 1000000;
int mark[N] = {0};
struct node
{
    int x;
    int time;
};
int check(int x)
{
    if(x > N || x < 0 || mark[x] == 1)
        return 0;
    else
        return 1;
}

int bfs(int x)
{
    node p,nextp;
    queue<node> Q;
    p.x = x;
    p.time = 0;
    mark[x] = 1;
    Q.push(p);
    while(!Q.empty())
    {
        p = Q.front();
        Q.pop();
        if(p.x == k)
        {
            return p.time;
        }
        nextp.x = p.x+1;
        if(check(nextp.x))
        {
            nextp.time = p.time+1;
            Q.push(nextp);
            mark[nextp.x] = 1;
        }
        nextp.x = p.x-1;
        if(check(nextp.x))
        {
            nextp.time = p.time+1;
            Q.push(nextp);
            mark[nextp.x] = 1;
        }
        nextp.x = p.x*2;
        if(check(nextp.x))
        {
            nextp.time = p.time+1;
            Q.push(nextp);
            mark[nextp.x] = 1;
        }
    }
    return -1;
}

int main()
{
    while(cin>>n>>k)
    {
        memset(mark,0,sizeof(mark));
        int ans = bfs(n);
        cout<<ans<<endl;
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值