fork download
  1. #include <iostream>
  2. #include <queue>
  3. #include <stack>
  4. #include <cstring>
  5. using namespace std;
  6.  
  7. int visited[100001];
  8. queue<int> q;
  9.  
  10. int bfs(int n, int m){
  11.  
  12. int time=0;
  13. q.push(n);
  14. while(true){
  15.  
  16. int size=q.size();
  17. for(int i=0; i<size; i++){
  18. n=q.front();
  19. q.pop();
  20. if(n==m){
  21. return time;
  22. }
  23. if(n-1>=0 && visited[n-1]==0){
  24. visited[n-1]=1;
  25. q.push(n-1);
  26. }
  27. if(n+1<=100000 && visited[n+1]==0){
  28. visited[n+1]=1;
  29. q.push(n+1);
  30. }
  31. if(n*2<100001 && visited[n*2]==0){
  32. visited[n*2]=1;
  33. q.push(n*2);
  34. }
  35. }
  36. time++;
  37. }
  38. }
  39.  
  40. int main() {
  41.  
  42. int n,k;
  43. cin>>n>>k;
  44. cout << bfs(n,k) << endl;
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0s 4520KB
stdin
1 4
stdout
2