2717:Catch That Cow
2015-09-28 10:58
246 查看
题目链接: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
方法: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 = {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; } }
相关文章推荐
- Spring Batch Tasklet example(二)
- 字符串,switch
- 架构师和数学
- 前端开发过程中的一些小知识点总结
- 检测到有潜在危险的 Request.Form 值
- Cookie对象HttpOnly和secure属性
- 二叉树的镜像
- CISCO_CVoice – 005:Translation Rule 和命中法则
- 简单易懂的jquery版三级联动select
- 解决eclipse快捷方式无法启动
- Windows系统U盘写保护
- [codevs2442] kshort 经典题
- 设置国内的centos 7 yum源
- ARC forbids explicit message send of 'retainCount'
- Win7下安装,配置Java, Ant,Maven
- Activity的tab分页生命周期
- UITextView的属性
- Java中的23种设计模式
- Matlab网格划分程序Distmesh讲解(一)
- dia在linux中无法输入中文