题目描述
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?
输入
Line 1: Two space-separated integers: N and K
输出
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.
题解
题目的意思是:输入N和K,其中N代表起点,K代表终点,N每次只能+1,-1或者 x 2,问至少需要几步才能得到K。 (0 ≤ N,K ≤ 100,000)
例如输入5 17,那么最少步数为4。走的方法为:(1)5 x 2=10 ,(2)10-1=9,(3)9 x 2 =18,(4)18-1=17
思路很简单,利用BFS遍历起点能到达的点,再由这些点遍历到其他点,当遍历到终点时就得到答案了。
代码
#include<iostream>
using namespace std;
#include<queue>
#include<string>
int n, k; //当前位置,目标位置
bool vis[100005]; //标记数组
struct node
{
int x, step; //当前位置,已走步数
};
bool check(int a) //检测当前位置是否合法
{
if (a < 0 || a>100000 || vis[a])
return false;
return true;
}
int bfs(int x)
{
node now, next;
vis[x] = true; //当前位置已访问 标记置为真
now.x = x, now.step = 0;
queue<node>q; //创建队列q
q.push(now); //将当前位置放入队列
while (!q.empty())
{
now = q.front(); //取队首元素
q.pop(); //删除队首元素
if (now.x == k)return now.step; //判断当前位置是否走到目标位置 走到了就返回走的步数
next.x = now.x + 1; //前进
if (check(next.x)) //判断走的位置是否合法
{
next.step = now.step + 1; //步数加1
vis[next.x] = 1; //当前位置已访问 标记置为真
q.push(next); //将该点放入队列
}
next.x = now.x - 1; //后退
if (check(next.x))
{
next.step = now.step + 1;
vis[next.x] = 1;
q.push(next);
}
next.x = now.x*2; //传送
if (check(next.x))
{
next.step = now.step + 1;
vis[next.x] = 1;
q.push(next);
}
}
return -1;
}
int main()
{
cin >> n >> k; //输入
memset(vis,0,sizeof(vis)); //标记数组全部置0
int res = bfs(n); //调用bfs
cout << res << endl;
//system("pause");
return 0;
}