农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上,农夫起始位于点N(0<=N<=100000),牛位于点K(0<=K<=100000)。农夫有两种移动方式:
1、从X移动到X-1或X+1,每次移动花费一分钟
2、从X移动到2*X,每次移动花费一分钟
假设牛没有意识到农夫的行动,站在原地不动。农夫最少要花多少时间才能抓住牛?
输入格式:
两个整数,N和K
输出格式:
一个整数,农夫抓到牛所要花费的最小分钟数
输入样例:
在这里给出一组输入。例如:
5 17
输出样例:
在这里给出相应的输出。例如:
4
解题思路:
直接bfs解决;
1,起点入队
2,将起点可走的循环入队
3,头出队
4,循环2,3直到对为空,并判断出最小步数
c++代码如下:
#include <bits/stdc++.h>
#define elemtype int
using namespace std;
struct point
{
point(int a,int b)
:_x(a)
,_step(b)
{
}
int _x;
int _step;
};
elemtype arrA[9999999];
deque<point> d;
int min = 9999999;
int cow,man;
void BFS(deque<point> d)
{
while(!d.empty())
{
int x = d.begin()->_x;
int step = d.begin()->_step;
if(x == cow)
{
if(step < ::min)
{
::min = step;
}
}
//x+1
if(arrA[x+1] == 0 && x+1 <= cow*2)
{
d.push_back(point(x+1,step+1));
arrA[x+1] = 1;
}
//x-1
if(arrA[x-1] == 0 && x-1 >= 0)
{
d.push_back(point(x-1,step+1));
arrA[x-1] = 1;
}
//2*x
if(arrA[x*2] == 0 && x*2 <= cow*2)
{
d.push_back(point(x*2,step+1));
arrA[x+1] = 1;
}
d.erase(d.begin());
}
};
int main()
{
cin >> man >> cow;
::memset(arrA,0,sizeof(arrA));
//入队
d.push_front(point(man,0));
arrA[man] = 1;
BFS(d);
cout << ::min;
}