题目大意:
输入n和k,分别为Famer John的位置和牛的位置。FJ只有三种去追牛的方法,分别为n-1, n+1, n*2的走法。问FJ怎么追能够步数最少,并输出最少步数。
解题思路:
拿到这个题,因为是找最少步数,就想到了要用BFS。但需注意的是,因为数组定义的特别大,所以要定成全局变量,否则无法执行。
代码实现:
#include <iostream>
#include <fstream>
#include <cstdio>
#include <queue>
#include <memory.h>
#define MAX 100005
using namespace std;
queue<int> q;
int step[MAX]; //跟随数组,记录步数
bool visit[MAX];
int n,k;
int next,head;
int bfs()
{
q.push(n);
step[n]=0;
visit[n]=1;
while(!q.empty())
{
head=q.front();
q.pop();
for(int i=0; i<3 ;i++)
//分三个方向BFS
{
if(i==0) next=head-1;
else if(i==1) next=head+1;
else next=head*2;
if(next>MAX || next<0 ) continue; //必须先判断,不然会RE,数组越界了
if(!visit[next])
{
q.push(next);
step[next]=step[head]+1;
visit[next]=1;
}
if(next==k) return step[next];
}
}
return -1;
}
int main()
{
memset(visit,0,sizeof(visit));
scanf("%ld%ld",&n,&k);//要注意输入方式
if(n>=k)
{
printf("%d",n-k);
}
else
{
printf("%d",bfs());
}
return 0;
}