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?
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
这个题与B相比比较简单,BFS。
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int N = 1000000;
int vis[N+10];
int n,k;
int to[3] = {1, -1, 0};
struct loc
{
int x, level;
};
int checktrue(int num)
{
if(num<0 || num>=N || vis[num])
return 0;
return 1;
}
int bfs(int m)
{
queue<loc> srch;
loc curNum, nxt;
curNum.x = m;
curNum.level = 0;
vis[m] = 1;
srch.push(curNum);
while(!srch.empty())
{
curNum = srch.front();
srch.pop();
if(curNum.x == k)
return curNum.level;
nxt = curNum;
to[2] = curNum.x;
for(int i = 0; i < 3; i++)
{
nxt.x = curNum.x + to[i];
if(checktrue(nxt.x))
{
nxt.level = curNum.level+1;
vis[nxt.x] = 1;
srch.push(nxt);
}
}
}
return -1;
}
int main()
{
while(~scanf("%d %d", &n, &k))
{
memset(vis, 0, sizeof(vis));
printf("%d\n", bfs(n));
}
return 0;
}