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.
题目大意:农夫被告知逃亡奶牛的文职,并希望能够立即抓住奶牛。他刚开始站在点N(0<= N <= 100000)上,母牛站在同一条线的点K上,农夫有两种交通方式:步行和传送。
- 行走:可以在一分钟内从任一点X移动到X-1或X+1。
- 传送:可以在一分钟内从任一点X移动到2X点。
如果母牛不知道有人要去追它,根本不动,那么农夫需多长时间找到他。
分析:即求找到奶牛的最短时间。已知农夫的状态可以用一个二元组来表示(n,t),其中n是农夫所在的位置,t是N到n所耗费时间。从当前状态到下一状态可以有三种状态(n-1,t+1),(n+1,t+1),(2*n,t+1)。目标状态是(K,最短时间)把每下一层状态用树来表示,则每一层的时间都是一样的,那么按照宽度优先搜索的方式查找,当查找到K时,时间必定是最短时间。
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int MAXN = 100010 ;
struct Status{ //状态二元组
int n,t; //分别表示现在的位置,以及走过的时间。
Status(int n,int t):n(n),t(t) {} //构造函数
};
bool visit[MAXN]; //来判断当前位置是否已经访问过,避免重复判断
int BFS(int n,int k){
queue<Status> myQueue ; //使用队列来进行宽度优先搜索
myQueue.push(Status(n,0)); //当前状态入队。
visit[n] = true; //已经入队的位置就不会再重复入队。
while(!myQueue.empty()){
Status current = myQueue.front();//队列第一个元素
myQueue.pop();//弹出
if(current.n == k){
return current.t;
}
for(int i = 0 ; i < 3;i++){ //三个状态 之后均入队
Status next(current.n,current.t+1);
if(i == 0){
next.n -= 1;
}else if(i == 1){
next.n += 1;
}else{
next.n *= 2;
}
if(next.n < 0 || next.n >= MAXN || visit[next.n]){
continue; //状态不合法,则不做操作。
}
myQueue.push(next);
visit[next.n] = true;
}
}
}
int main()
{
int n,k;
cin>>n>>k;
memset(visit,false,sizeof(visit)); //初试化,cstring
cout<<BFS(n,k)<<endl;
return 0;
}
宽度优先搜序相关:
玛雅人的密码:牛客网