题目

acwing1100. 抓住那头牛

题解

#include<iostream>
#include<cstring>
using namespace std;
const int N=1e5+10;
int n,k;
int q[N],cost[N];
bool st[N];
int  bfs(){
    memset(cost,-1,sizeof cost);
   int hh=0,tt=0;
   q[0]=n;
   cost[n]=0;
   while(hh<=tt){
       int t=q[hh++];
       if(t==k)return cost[t];
       if(t+1<N&&cost[t+1]==-1){
           q[++tt]=t+1;
           cost[t+1]=cost[t]+1;
       }
       if(t-1>=0&&cost[t-1]==-1){
           q[++tt]=t-1;
           cost[t-1]=cost[t]+1;
       }
       if(t<<1<N&&cost[t<<1]==-1){
           q[++tt]=t<<1;
           cost[t<<1]=cost[t]+1;
       }
   }
   return -1;
}
int main(){
    cin>>n>>k;
    cout<<bfs()<<endl;
    return 0;
}