RE力
题目: 在一条笔直的道路上,有一位农夫和一头牛,笔直的道路可以视为数轴(x 轴),农夫的坐标为 N,牛的坐标为 K。现在农夫想抓住那头牛,但农夫却只有以下两种移动方式:
假设当前坐标为 x,那么花一分钟,可以移动到 x−1 或 x+1 处 假设当前坐标为 x,那么花一分钟,可以移动到 2x 处 问:农夫最少要花多少分钟才能抓住牛?
#include<bits/stdc++.h>
using namespace std;
struct bfs{
int x,t;
};
queue<bfs> q;
int n,k;
bool vis[100001];
int BFS(){
int x,t;
vis[n]=true;
q.push({n,1});
while(!q.empty()){
x=q.front().x;
t=q.front().t;
q.pop();
if(x==k-1) return t;
for(int i=0,fx;i<3;i++){
if(i==0) fx+=1;
else if(i==1) fx-=1;
else if(i==2) fx*=2;
if(fx<0 || fx>k) continue;
if(!vis[fx]){
vis[fx]=true;
q.push({fx,t+1});
}
}
}
}
int main(){
scanf("%d%d",&n,&k);
printf("%d",BFS());
return 0;
}