这道题可以采用BFS的思想,因为农夫走的方法只有三种,即-1,+1,*2,依次执行三种操作,然后判断是否到达k点,若到达则输出花费的时间,否则继续:
#include <iostream>
#include <string>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1e5 + 10;
struct Statue{
int position;
int time;
Statue(){}
Statue(int p, int t): position(p), time(t){}
};
bool visited[N];
int BFS(int n, int k){
queue<Statue> q;
q.push(Statue(n, 0));
visited[n] = true;
while(!q.empty()){
Statue current = q.front();
if(current.position == k) return current.time;
q.pop();
for(int i = 0; i < 3; i++){
Statue next = current;
if(i == 0) next.position -= 1;
else if(i == 1) next.position += 1;
else next.position *= 2;
next.time += 1;
if(next.position < 0 || next.position > 1e5 || visited[next.position]) continue; //若新状态非法,则丢弃
q.push(next);
visited[next.position] = true;
}
}
}
int main(){
int n, k;
scanf("%d%d", &n, &k);
memset(visited, false, sizeof(visited));
printf("%d\n", BFS(n, k));
return 0;
}