poj 3278 bfs 标记数组
2016-06-03 13:32
169 查看
第一道bfs的题,哈哈,貌似大家都是
可知移动一次可以有三种操作选择,就把它加到队列里头,每循环一次,取出队头并出队,
创建一个标记数组用来记录这个点有没有访问到,因为第一次访问到的地方所用的步数是最小的,即使之后用其他的操作同样可以走到,同时用它来记录步数,因为0表示没有访问,非0表示已经访问过
可知移动一次可以有三种操作选择,就把它加到队列里头,每循环一次,取出队头并出队,
创建一个标记数组用来记录这个点有没有访问到,因为第一次访问到的地方所用的步数是最小的,即使之后用其他的操作同样可以走到,同时用它来记录步数,因为0表示没有访问,非0表示已经访问过
如果n>=k 输出n-k 因为只能往回走
注意 数组要开大点,因为当k=100000时 假设其中某一步通过*2走到了100099,往回走要比在上一状态单纯+1所用的步数少
#include<map> #include<set> #include<queue> #include<stack> #include<cmath> #include<cstdio> #include<string> #include<vector> #include<cstring> #include<iostream> #include<algorithm> using namespace std; int vis[100104]; int main() { int n,k; while(scanf("%d%d",&n,&k)!=EOF) { if(n>=k) { printf("%d\n",n-k); } else { queue<int> q; q.push(n); int step=0; int cnt=0; memset(vis,0,sizeof(vis)); while(!q.empty()) { cnt++; step=q.front(); q.pop(); int step1; if(step+1<=100100&&!vis[step+1]) { vis[step+1]=vis[step]+1; if(step+1==k) break; q.push(step+1); } if(step-1>=0&&!vis[step-1]) { vis[step-1]=vis[step]+1; if(step-1==k) break; q.push(step-1); } if(step*2<100100&&!vis[step*2]) { vis[step*2]=vis[step]+1; if(step*2==k) break; q.push(step*2); } } printf("%d\n",vis[k]); } } return 0; }
相关文章推荐
- Python编程规范
- 数据库常用操作
- springmvc集成JSR-303的解析消息文件的默认实现浅析
- PhoneGap中"unable to download archive from the server. "警告的解决方法
- Android 自定义view设置xml属性
- 选择排序和插入排序
- matlab之plot、fplot、ezplot函数
- Android事件传递机制以及ViewGroup的onInterceptTouchEvent的理解
- SQL Server优化50法
- sql语句基础要点(以sql server 2008 为例)
- 如何用#define宏定义多行函数
- Ubuntu16.04 安装flash player
- 低代码平台,到底能给企业带来什么?
- Apache服务器访问权限设置
- js date 操作
- 操作linux redis 常用命令
- iOS多级跳转,返回指定viewcontroller
- spring源码解析
- 利用scipy.sparse.csr_matrix构建term-document matrix
- C语言结构体打包的意义