问题:抓住那头牛
农夫知道一头牛的位置,想要抓住它。农夫和牛都于数轴上 ,农夫起始位于点 N(0<=N<=100000) ,牛位于点 K(0<=K<=100000) 。农夫有两种移动方式: 1、从 X移动到 X-1或X+1 ,每次移动花费一分钟 2、从 X移动到 2*X ,每次移动花费一分钟 假设牛没有意识到农夫的行动,站在原地不动。最少要花多少时间才能抓住牛?
Input
一行: 以空格分隔的两个字母: N 和 K
Output
一行: 农夫抓住牛需要的最少时间,单位分钟
Sample Input
5 17
Sample Output
4
提示
农夫使用最短时间抓住牛的方案如下: 5-10-9-18-17, 需要4分钟.
解题代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#define max_n 100001
using namespace std;
int select[3]; //移动方式
int time[max_n]; //存储到达对应点的时间,且为0时表示未访问
int bfs(int n, int k)
{
if(n == k) //若当前结点为终点,返回0
return 0;
queue<int> que;
que.push(n);
while(!que.empty())
{
int cur = que.front();
que.pop();
//三种移动方式
select[0] = cur - 1;
select[1] = cur + 1;
select[2] = cur * 2;
//对任意的三种方式进行bfs遍历
for(int i = 0; i < 3; i++) {
//越界与是否访问判断
if(select[i] >= 0 && select[i] < max_n && time[select[i]] == 0) {
que.push(select[i]);
time[select[i]] = time[cur] + 1; //时间加1
}
}
}
return time[k]; //返回到达终点时间
}
int main()
{
int n, k;
while(~scanf("%d%d",&n,&k))
{
memset(time, 0, sizeof(time)); //初始化时间为0
int res = bfs(n,k);
cout << res << endl;
}
return 0;
}
感谢你的访问!