题目描述
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point
on a number line and the cow is at a point
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?
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.
示例1
输入
5 17
输出
4
解答
提示:Farmer John到达逃亡牛的最快方法是沿着以下路径移动:5-10-9-18-17,需要4分钟。
思路:
这个是BFS的基本简单题,意思就是农夫在位置N处,而母牛在位置K处,解决这道题首先要建立一个结构体关于农夫的位置和农夫总共走的步数。再定义一个检查的函数,当如果x越界或者是这个点已经走过的话,那么就返回0,反之返回1。最后定义一个bfs的函数,首先要将队列清空,然后做判断,如果当前农夫的位置和母牛的位置相同的时候,直接返回步数,不符合这个情况的话,开始n-1,n+1,和2*n的三种情况的分类讨论,但三种讨论的话里面的东西都是一样的。下面上代码:
实质上就是结构体队列的应用:
这个是BFS的基本简单题,意思就是农夫在位置N处,而母牛在位置K处,解决这道题首先要建立一个结构体关于农夫的位置和农夫总共走的步数。再定义一个检查的函数,当如果x越界或者是这个点已经走过的话,那么就返回0,反之返回1。最后定义一个bfs的函数,首先要将队列清空,然后做判断,如果当前农夫的位置和母牛的位置相同的时候,直接返回步数,不符合这个情况的话,开始n-1,n+1,和2*n的三种情况的分类讨论,但三种讨论的话里面的东西都是一样的。下面上代码:
实质上就是结构体队列的应用:
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<stack>
#include <queue>
using namespace std;
const int N = 1000000;
int map[1000001];//走过的标记1.没走过的标记0
int n,k;//n是农夫的位置,k是母牛的位置
struct node//定义一个结构体记录位置和步数的
{
int x,step;
};
//check函数结果如果是0的话,第一就是越界,第二个就是这个点已经走过了
int check(int x)
{
if(x<0 || x>=N || map[x])
return 0;
return 1;
}
int bfs(int x)
{
int i;
queue<node> q;//把q队列化
node a,next;//把a,next作为结构体
a.x = x;//结构体a初始化
a.step = 0;
map[x] = 1;//刚开始的点标记为1
q.push(a);//把a加入到队列的末尾
while(!q.empty())
{
a = q.front();//先把队首读取
q.pop();//弹出对首
if(a.x == k)//如果农夫的位置和母牛的位置相同的话
return a.step;//直接返回步数
next = a;
//每次都将三种状况加入队列之中
//1.这个是+1的情况
next.x = a.x+1;
if(check(next.x))//无论是什么情况下这几行代码都是一样的
{
next.step = a.step+1;//这个就是步数+1
map[next.x] = 1;//表示已经走过了这个点
q.push(next);//把next结构体加入队列
}
next.x = a.x-1;
if(check(next.x))
{
next.step = a.step+1;
map[next.x] = 1;
q.push(next);
}
next.x = a.x*2;
if(check(next.x))
{
next.step = a.step+1;
map[next.x] = 1;
q.push(next);
}
}
}
int main()
{
int ans;//统计最后的步数
while(~scanf("%d%d",&n,&k))//n指的是农夫的位置,k指的是母牛的位置
{
memset(map,0,sizeof(map));//数组初始化
ans = bfs(n);
printf("%d\n",ans);
}
return 0;
} 来源:rnzhiw

京公网安备 11010502036488号