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; }
相关文章推荐
- Android使用xUtils方便地下载 / xUtils介绍
- Media Formatters
- 第一百二十七天 how can I 坚持
- C#实现ActiveX控件开发与部署
- 谈谈java垃圾回收机制
- 越狱开发-创建真正的后台程序(Daemon Process)
- 劫持系统函数system
- java学习笔记——String类
- python开发_counter()
- 下拉框选择效果的实现原理
- 位操作基础篇之位操作全面总结
- 动画延迟消失
- JavaScript高级程序设计 读书笔记 第二章
- 课后作业 06 -- 小数后几位精确判断并输出
- 黑马程序员--多线程总结2--java
- 《Objective-C基础教程》第5章 复合
- Leetcode # 103 Binary Tree Zigzag Level Order Traversal
- web api 参数绑定
- java学习笔记——内部类
- 在寝室的追忆与思考