fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int const NMAX = 2e6;
  6. int moves[1 + NMAX];
  7. int n, from;
  8. queue<int> q;
  9.  
  10. bool isValid(int to) {
  11. return 1 <= to && to <= NMAX;
  12. }
  13.  
  14. void visit(int to) {
  15. if(isValid(to) && moves[to] == 0) {
  16. moves[to] = moves[from]+1;
  17. q.push(to);
  18. }
  19. }
  20.  
  21. int main() {
  22. cin >> n;
  23. q.push(1);
  24. while(true) {
  25. from = q.front();
  26. if(from == n) {
  27. cout << moves[from];
  28. return 0;
  29. }
  30. q.pop();
  31. visit(from-1);
  32. visit(from+1);
  33. visit(3*from);
  34. }
  35. }
Success #stdin #stdout 0s 5288KB
stdin
14
stdout
5