HDU 2717 Catch That Cow

来源:互联网 发布:怎么关掉苹果电脑软件 编辑:程序博客网 时间:2024/06/08 13:52

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 1000005bool 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;}


0 0
原创粉丝点击