HDU 2717 Catch That Cow

Catch That Cow

Problem Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

* Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
 

Input
Line 1: Two space-separated integers: N and K
 

Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
 

Sample Input
5 17
 

Sample Output
4


【思路分析】
   这是一个带有贪心策略的bfs问题。在做这个题的时候千万不能随便就将bfs下一层的所有结点直接入队,这样会导致MLE(这个错误各种修改后才发现,有点蛋疼),结点入队之前一定要判断这个结点是否满足题目给定的范围而且相同结点只入队一次,这样就能大大减少队列的长度从而减少内存。具体操作中可以设置一个bool类型的flag数组,flag[i]表示i这个数字是否出现在队列中,如果为false,则将i入队并修改为true,否则不入队。

代码如下:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <queue>
#include <algorithm>
using namespace std;
#define maxn 1000005
bool flag[maxn];
struct Node
{
    int index;
    int pos;
};
int main()
{
    int n,k,ans,first;
    queue<Node> q;
    Node node,temp;
    while(scanf("%d %d",&n,&k) != EOF)
    {
        memset(flag,false,sizeof(flag));
        node.index = n;
        node.pos = 0;
        flag[n] = true;
        q.push(node);
        while(!q.empty())
        {
            node = q.front();
            q.pop();
            first = node.index;
            if(first == k)
            {
                ans = node.pos;
                break;
            }
            if(first - 1 >= 0 && flag[first - 1] == false)
            {//满足范围并且没有入过队列的点才可入队,防止MLE
                temp.index = first - 1;
                temp.pos = (node.pos + 1);
                flag[first - 1] = true;
                q.push(temp);
            }

            if(first + 1 <= maxn && flag[first + 1] == false)
            {
                temp.index = first + 1;
                temp.pos = (node.pos + 1);
                flag[first + 1] = true;
                q.push(temp);
            }

            if(first * 2 <= maxn && flag[2 * first] == false)
            {
                temp.index = first * 2;
                temp.pos = (node.pos + 1);
                flag[first * 2] = true;
                q.push(temp);
            }

        }
        printf("%d\n",ans);
        while(!q.empty())
        {
            q.pop();
        }
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值