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.
题目大意:
John想要抓牛
开始输入N K。
N为John的初始位置。
K为奶牛的位置。
求抓到奶牛所用的最短时间。John有三种移动方法: 1、向前走一步,耗时一分钟。 2、向后走一步,耗时一分钟。 3、向前移动到当前位置的两倍,耗时一分钟。
思路:
1、如果John不在奶牛的后面,那么他只能向后移动,直到抓到奶牛。即N>=K时,输出N-K即可。
2、如果John在奶牛的后面,就按照上述的三种方法移动,直至抓到奶牛。(这里就用到了bfs和队列)
BFS的思想:
1.从初始状态S开始,利用规则,生成下一层的状态。
2.顺序检查下一层的所有状态,看是否出现目标状态G。否则就对该层所有状态节点,分别利用规则。生成再下一层的所有状 态节点。
3.继续按上面思想生成再下一层的所有状态节点,这样一层一层往下展开。直到出现目标状态为止。
按层次的顺序来遍历搜索树
BFS框架
通常用队列(先进先出,FIFO)实现
初始化队列Q.
Q={起点s}; 标记s为己访问;
while (Q非空) {
取Q队首元素u;
u出队;
if (u == 目标状态) {…}
所有与u相邻且未被访问的点进入队列;
标记u为已访问;
}
完整代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int N = 200100;
int n, k;
struct node
{
int x, step;
};
queue<node> Q;
int vis[N];
void BFS()
{
int X, STEP;
while(!Q.empty())
{
node w2= Q.front();
Q.pop();
X = w2.x;
STEP = w2.step;
if(X == k)
{
printf("%d\n",STEP);
return ;
}
if(X >= 1 && vis[X - 1]==0)
{
node w3;
vis[X - 1] = 1;
w3.x = X - 1;
w3.step = STEP + 1;
Q.push(w3);
}
if(X <= k && vis[X + 1]==0)
{
node w3;
vis[X + 1] = 1;
w3.x = X + 1;
w3.step = STEP + 1;
Q.push(w3);
}
if(X <= k && vis[X * 2]==0)
{
node w3;
vis[X * 2] = 1;
w3.x = 2 * X;
w3.step = STEP + 1;
Q.push(w3);
}
}
}
int main()
{
while(scanf("%d%d",&n,&k)!=EOF)
{
while(!Q.empty())
Q.pop();
memset(vis,0,sizeof(vis));
vis[n] = 1;
node w1;
w1.x = n;
w1.step = 0;
Q.push(w1);
BFS();
}
return 0;
}