您的位置:首页 > 其它

HDU 2717 Catch That Cow

2015-08-08 00:31 417 查看

Catch That Cow

[align=left]Problem Description[/align]

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?
 

[align=left]Input[/align]

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

[align=left]Output[/align]

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

[align=left]Sample Input[/align]

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
= 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;
}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: