Catch That Cow
Problem 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?
* 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.题目描述:找最短步数,用bfs
#include<iostream> #include<algorithm> #include<string.h> #include<queue> using namespace std; int n, k,ans,step[200010],book[200010]; //wa了好几次,这里一定要大一点 ,step:步数 book:标记走没走 void bfs(int a, int b) { ans = 0; book[a] = 1; queue<int >q; q.push(a); while (!q.empty()) { int x = q.front(); //cout <<x<<" "<<b<<"\n"; q.pop(); if( x== b)break; if (x * 2 <= 200010 && x * 2 >= 0 && book[x * 2] == 0) { //判断边界,判断走没走, book[2 * x] = 1; q.push(x * 2); step[x * 2] = step[x] + 1; } if (x + 1 <= 200010 && x + 1 >= 0 && book[x + 1] == 0) { //判断边界,判断走没走, book[1 + x] = 1; q.push(x +1); step[x + 1] = step[x] + 1; } if (x - 1 <= 200010 && x - 1 >= 0 && book[x - 1] == 0) { //判断边界,判断走没走, book[x - 1] = 1; q.push(x -1); step[x - 1] = step[x] + 1; } } } int main() { while (cin >> n >> k) { memset(step, 0, sizeof(step)); //不要忘记初始化 memset(book, 0, sizeof(book)); if (n >= k)cout << n - k << endl; //n不大于k的话 就是n-k了 else { bfs(n, k); cout << step[k] << endl; } } return 0; }