Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

Блог пользователя abelmul

Автор abelmul, история, 18 месяцев назад, По-английски

The question asks if we can reach a number n from a number m by multiplying n by either 2 or 3

We can think of the problem as a path finding operation from the number n and m.

We can do that using recursion so we calculate all paths and we return the max of the solutions.

    #include <bits/stdc++.h>
     
    using namespace std;
     
    int solve(int n, int m, int moves = 0)
    {
        if (n > m) {
            return -1;
        }
     
        if (n == m) {
            return moves;
        }
     
        // solve for n * 2
        int n2 = solve(n * 2, m, moves + 1);
     
        // solve for n * 3
        int n3 = solve(n * 3, m, moves + 1);
     
        return max(n2, n3);
    }
     
    int main()
    {
        int n, m;
     
        ios::sync_with_stdio(false);
        cin.tie(0);
     
        cin >> n >> m;
     
        cout << solve(n, m) << "\n";
     
        return 0;
    }

A more performant version will be to use backtracking. Which will can implement as

  int solve(int n, int m, int moves = 0)
  {
      if (n > m) {
          return -1;
      }

      if (n == m) {
          return moves;
      }

      int res;

      // pick 2
      res = solve(n * 2, m, moves + 1);

      if (res == -1) {
          // pick 3
          res = solve(n * 3, m, moves + 1);
      }

      return res;
  }

Полный текст и комментарии »

  • Проголосовать: нравится
  • -8
  • Проголосовать: не нравится