上题目
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
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.
翻译
初始值为i 终点j
你所能进行的移动是 ±1 或者 乘2
问从i 到j 的最短路径问题
分析
标准的bfs(求最短路径)
不过我们可以设置i > 0; j < 0
然后对于 +1; - 1; * 2 三种情况依次压栈
求到达j点的最小操作次数
上代码 + 注释
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int vis[100000];
int flag, start, endd;
struct k{//用来存储当前的位置和步数
int x;
int countt;
};
int bfs()
{
memset(vis, 0, sizeof(vis));
queue <k>q;
k now, next;
now.countt = 0;
now.x = start;
q.push(now);
while (!q.empty())
{
now = q.front();
q.pop();
if (now.x == endd)
return now.countt;
if (now.x < 0 || now.x > 1000000)//出界
continue;
if (vis[now.x] == 1)//已经被访问
continue;
vis[start] = 1;
vis[now.x] = 1;
next.x = now.x - 1;//向 -1 方向移动
next.countt = now.countt + 1;
q.push(next);
next.x = now.x + 1;//向 +1 方向移动
next.countt = now.countt + 1;
q.push(next);
next.x = now.x * 2;//向 * 2 方向移动
next.countt = now.countt + 1;
q.push(next);
}//直至队列为空
}
int main(void)
{
while (scanf("%d %d", &start, &endd) != EOF)
{
int cnt;
cnt = bfs();
printf("%d\n", cnt);
}
return 0;
}