43 lines
973 B
C++
43 lines
973 B
C++
#include <bits/stdc++.h>
|
||
using namespace std;
|
||
|
||
const int N = 2e5 + 10;
|
||
const int INF = 0x3f3f3f3f;
|
||
int n, k;
|
||
int q[N];
|
||
int dist[N];
|
||
int Min = INF;
|
||
int bfs() {
|
||
//初始化距离数组-1
|
||
memset(dist, -1, sizeof dist);
|
||
|
||
int hh = 0, tt = -1;
|
||
q[++tt] = n; //加入起点n
|
||
dist[n] = 0; // n距离出发点0个长度
|
||
|
||
while (hh <= tt) {
|
||
int t = q[hh++];
|
||
if (t == k) return dist[k];
|
||
if (t + 1 < N && dist[t + 1] == -1) {
|
||
dist[t + 1] = dist[t] + 1;
|
||
q[++tt] = t + 1;
|
||
}
|
||
if (t - 1 >= 0 && dist[t - 1] == -1) {
|
||
dist[t - 1] = dist[t] + 1;
|
||
q[++tt] = t - 1;
|
||
}
|
||
if (t * 2 < N && dist[t * 2] == -1) {
|
||
dist[t * 2] = dist[t] + 1;
|
||
q[++tt] = t * 2;
|
||
}
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
int main() {
|
||
//农夫起始位于点N,牛位于点K
|
||
cin >> n >> k;
|
||
printf("%d\n", bfs());
|
||
return 0;
|
||
}
|