BFS-1
来源:互联网 发布:python oxc000007b 编辑:程序博客网 时间:2024/06/05 11:39
https://vjudge.net/problem/15204/origin
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN (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 orX + 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?
Line 1: Two space-separated integers: N andK
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
5 17
4
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
#include <iostream>#include <queue>#include <cstdio>using namespace std;const int MAX_N=1e5;int N,K;int ans[MAX_N+1];int BFS(){ queue<int>que; for(int i=0;i<=MAX_N;i++){ ans[i]=0; } que.push(N); while(que.size()){ int tp=que.front();que.pop(); if(tp==K) break; if(tp+1<=100000&&ans[tp+1]==0){ ans[tp+1]=ans[tp]+1; que.push(tp+1); } if(tp-1>=0&&ans[tp-1]==0){ ans[tp-1]=ans[tp]+1; que.push(tp-1); } if(tp*2<=100000&&ans[tp*2]==0){ ans[tp*2]=ans[tp]+1; que.push(tp*2); } } return ans[K];}int main(){ while(~scanf("%d%d",&N,&K)){ cout<<BFS()<<endl; } return 0;}这是我仿照迷宫最短路径问题写的代码,要理解DFS为什么要用队列的数据结构;
0 0
- BFS-1
- 1poj1426(bfs||dfs)
- 1poj2243(bfs)
- POJ_S1E03_DFS&BFS(1)
- dfs与bfs(1)
- 0-1bfs
- BFS
- bfs
- BFS
- BFS
- bfs
- BFS
- bfs
- BFS
- BFS
- bfs
- BFS
- BFS
- vue2.0多条件搜索组件
- 【HDU 2438】 Turn the corner
- ubuntu16.04 切换 python 版本
- Hashtable 、ConcurrentHashMap源码学习
- java虚拟机--简单介绍
- BFS-1
- android电池剩余使用时间
- 539. Minimum Time Difference
- 二分图匹配——HDU 5943
- matlab面向对象教程【1】迷宫生成算法案例
- Mysql切换Oracle数据库
- Asp.net Core 打包发布 (Linux+Nginx)
- RAC11gR2Grid启动顺序及启动故障诊断思路
- 浅谈Android移动开发程序员的职业发展之路