Catch That Cow
HERE
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.
思路
BFS+队列优化。农夫每次可以选择的路有三种,向左向右传送。如果用DFS,三叉树搜索到底时间开太大,所以使用BFS。而且个人觉得BFS的泛用性优于DFS(可能是联练习的BFS比DFS多)
代码
#include <iostream>
#include <queue>
using namespace std;
struct aa
{
int x;
int sum;
};
int main()
{
int n=0,k=0;//农夫,牛坐标
cin>>n>>k;
bool flag[100005];//记录有没有去过,方便剪枝
fill(flag,flag+100000,true);
//初始化
aa temp,temp1;
temp.x=n;
temp.sum=0;
//队列优化
queue<aa> Q;
Q.push(temp);
flag[n]=false;
while (!Q.empty())
{
temp=Q.front();
Q.pop();
//结束条件
if (temp.x==k)
{
break;
}
//向左
if (temp.x-1>=0&&flag[temp.x-1])
{
flag[temp.x-1]=false;
temp1.x=temp.x-1;
temp1.sum=temp.sum+1;
Q.push(temp1);
}
//向右
if (temp.x+1<=100000&&flag[temp.x+1])
{
flag[temp.x+1]=false;
temp1.x=temp.x+1;
temp1.sum=temp.sum+1;
Q.push(temp1);
}
//传送
if (temp.x!=0&&temp.x*2<=100000&&flag[temp.x*2])
{
flag[temp.x*2]=false;
temp1.x=temp.x*2;
temp1.sum=temp.sum+1;
Q.push(temp1);
}
}
cout<<temp.sum;
return 0;
}