题目描述:
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
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
5 17
4
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和K的大小问题。
代码看了应该就能理解。
AC代码:
using namespace std;
int m,n;
int dr[ 2]={ 1, -1}; //前进和后退一步
int bj[s];
struct st
{
int x; //记录当前位置
int t; //记录搜索次数
};
int bfs(int a){
int i,dx;
memset(bj, 0, sizeof(bj));
queue<st> qu;
st now,ne;
now.x=a,now.t= 0;
qu.push(now);
bj[a]= 1; //标记初始搜索基点
while(!qu.empty())
{
now=qu.front();
qu.pop();
if(now.x==n)
return now.t; //搜索到目标点返回搜索次数
else
{
for(i= 0;i< 2;i++) //搜索前进一步和后退一步的点
{
dx=now.x+dr[i];
if(dx>= 0&&dx<= 100000) //不能超过题目限制
{
ne.x=dx;
ne.t=now.t;
if(dx==n)
return now.t+ 1;
if(bj[dx]== 0)
{
ne.t++;
qu.push(ne);
bj[dx]= 1;
}
}
}
dx=now.x* 2; //搜索前进2倍的点
if(dx>= 0&&dx<= 100000)
{
ne.x=dx;
if(dx==n)
return now.t+ 1;
ne.t=now.t;
if(bj[dx]== 0)
{
ne.t++;
qu.push(ne);
bj[dx]= 1;
}
}
}
}
}
int main() {
int i,j,sum,a,b;
scanf( "%d%d",&m,&n);
if(m>=n) //此时只能后退一步
printf( "%d\n",m-n);
else
{
sum=bfs(m);
printf( "%d\n",sum);
}
return 0;
}