A2SV Contest #16 — Problem D — Game 23

Правка en3, от abelmul, 2023-04-10 20:45:04

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;
  }

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en4 Английский abelmul 2023-04-10 20:45:37 0 (published)
en3 Английский abelmul 2023-04-10 20:45:04 462
en2 Английский abelmul 2023-04-10 20:39:17 807
en1 Английский abelmul 2023-04-10 20:35:00 279 Initial revision (saved to drafts)