广搜一下,把搜索范围控制好再10^5以内即可。
#include <iostream> #include <string> #include <cstdio> #include <algorithm> #include <vector> #include <stack> #include <queue> #define MAX 100005 #define mod 998244353ll #define INF 0x3f3f3f3f #define ll long long using namespace std; bool vis[MAX]; int n, m; int solve() { queue<int> q; q.push(n); int step = 0; while (1) { int si = q.size(); while (si--) { int t = q.front(); q.pop(); if (t * 2 == m) return step + 1; if (t * 2 < MAX && !vis[t * 2]) q.push(t * 2), vis[t * 2] = true; if (t - 1 == m) return step + 1; if (t - 1 > 0 && !vis[t - 1]) q.push(t - 1), vis[t - 1] = true; } step++; } return INF; } int main() { freopen("a.txt", "r", stdin); freopen("b.txt", "w", stdout); cin >> n >> m; cout << solve() << endl; return 0; }