题目
Description
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?
Input
Line 1: Two space-separated integers: N and K
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4
Hint
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.
题解
由于移动方式只有 +1 -1 *2 因此如果 起点大于终点,直接相减即可
剩下就是标准的BFS模板
代码
/* By:OhYee Github:OhYee Email:oyohyee@oyohyee.com Blog:http://www.cnblogs.com/ohyee/ かしこいかわいい? エリーチカ! 要写出来Хорошо的代码哦~ */ #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> #include <string> #include <iostream> #include <vector> #include <list> #include <queue> #include <stack> using namespace std; //DEBUG MODE #define debug 0 //循环 #define REP(n) for(int o=0;o<n;o++) const int maxn = 100005; int BFS(int s,int v) { if(s == v) return 0; if(s > v) return s - v; queue<int> Q; bool visited[maxn]; memset(visited,false,sizeof(visited)); int dis[maxn]; memset(dis,0,sizeof(dis)); Q.push(s); visited[s] = true; while(!Q.empty()) { int th = Q.front(); Q.pop(); //达到终点 if(th == v) break; //拓展节点 define push \ if(next > maxn || next <= 0) \ continue;\ if(!visited[next]) {\ Q.push(next);\ visited[next] = true;\ dis[next] = dis[th] + 1;\ }\ int next; next = th + 1; push; next = th - 1; push; next = th * 2; push; } if(dis[v]) return dis[v]; else return -1; } bool Do() { int s,v; if(scanf("%d%d",&s,&v)==EOF) return false; printf("%d\n",BFS(s,v)); return true; } int main() { while(Do()); return 0; }