解题思路:这题注意当位置大于牛位置时,x+1,x*2是不可取得,然后bfs即可。
代码:
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
#include<math.h>
const int mx=1e5+10,co[4][2]={1,0,0,1,-1,0,0,-1},inf = 1e9;
typedef long long ll;
using namespace std;
int n,m,size;
bool vis[mx<<1];
struct node{
int x,k;
node(){}
node(int xx,int kk){ x =xx, k = kk; }
};
int bfs(){
queue<node> skt;
skt.push(node(n,0));
memset(vis,0,sizeof(vis));
vis[n]=1;
while(!skt.empty()){
node no = skt.front(),to(no.x-1,no.k+1);
skt.pop();
if(to.x >= 0&&!vis[to.x]){
if(to.x==m) return to.k;
skt.push(to);
vis[to.x]=1;
}
if(no.x < m&&!vis[no.x+1]){
to.x = no.x+1;
if(to.x==m) return to.k;
skt.push(to);
vis[to.x]=1;
}
if(no.x < m&&!vis[2*no.x]){
to.x = 2*no.x;
if(to.x==m) return to.k;
skt.push(to);
vis[to.x]=1;
}
}
return 0;
}
int main(){
while(~scanf("%d%d",&n,&m)){
if(n==m) { puts("0"); continue; }
printf("%d\n",bfs());
}
return 0;
}