Farmer John想抓到一头牛,Farmer John在一个数轴的一个位子,牛在数轴的另一个位子。但Farmer John这个人在一个单位时间内可以有三种走的方式,一是走到数轴的下一格,或是前一格,或是他的数轴的两倍的格子上,为此人最快抓到牛的时间。点击打开链接
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstring>
using namespace std;
int start, end;
int index;
bool ok;
vector<int> V;
int digit[200001];
int bfs(int x,int step)
{
if(x==end)
{
ok =true;
return 0;
}
if(x-1>=0&&digit[x-1]==-1)
{
digit[x-1]=step+1;
V.push_back(x-1);
}
if(x+1<200001&&digit[x+1]==-1)
{
digit[x+1]=step+1;
V.push_back(x+1);
}
if(x*2<200001&&digit[x*2]==-1)
{
digit[x*2]=step+1;
V.push_back(2*x);
}
}
int main()
{
cin>>start>>end;
memset(digit, -1, sizeof(digit));
V.clear();
V.push_back(start);
digit[start] = 0;
index = 0;
ok = false;
while(!ok&&index<V.size()) //一层一层的搜索
{
bfs(V[index],digit[V[index]]);
index++;
}
cout<<digit[end]<<endl;
system("pause");
return 0;
}