fork download
  1. #include<bits/stdc++.h>
  2. #define PB push_back
  3. #define endl '\n';
  4. using ll = long long;
  5. using namespace std;
  6. const int maxN = 1e6;
  7. const int MOD = 1e9 + 7;
  8. int dx4[4] = {-1, 0, 0, 1};
  9. int dy4[4] = {0, -1, 1, 0};
  10. int dx8[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
  11. int dy8[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
  12. vector<bool> visited(maxN, false);
  13. vector<int> adj[maxN];
  14. vector<int> parent(maxN, 0);
  15. int n, m;
  16. int bfs(int n, int m){
  17. if(n >= m){
  18. return n - m;
  19. }
  20. queue<pair<int, int>> q;
  21. q.push(make_pair(n, 0));
  22. set<int> s;
  23. s.insert(n);
  24. while(!q.empty()){
  25. int x = q.front().first;
  26. int y = q.front().second;
  27. q.pop();
  28. if(x == m){
  29. return y;
  30. }
  31. if(s.find(x*2) == s.end()){
  32. q.push(make_pair(x*2, y + 1));
  33. s.insert(x*2);
  34. }
  35. if(x - 1 >= 0 && s.find(x - 1) == s.end()){
  36. q.push(make_pair(x - 1, y + 1));
  37. s.insert(x - 1);
  38. }
  39. }
  40. return -1;
  41. }
  42. int main() {
  43. ios_base::sync_with_stdio(0);
  44. cin.tie(nullptr);
  45. cout.tie(0);
  46. cin >> n >> m;
  47. cout << bfs(n, m);
  48. return 0;
  49. }
Success #stdin #stdout 0.01s 30500KB
stdin
2 7
stdout
3