Convierta N a M con operaciones dadas usando programación dinámica

Dados dos números enteros N y M , la tarea es convertir N a M con las siguientes operaciones: 

  1. Multiplique N por 2 , es decir , N = N * 2 .
  2. Reste 1 de N , es decir , N = N – 1 .

Ejemplos:  

Entrada: N = 4, M = 6 
Salida:
Realizar la operación 2: N = N – 1 = 4 – 1 = 3 
Realizar la operación 1: N = N * 2 = 3 * 2 = 6

Entrada: N = 10, M = 1 
Salida:

Enfoque: Cree una array dp[] de tamaño MAX = 10 5 + 5 para almacenar la respuesta a fin de evitar el mismo cálculo una y otra vez e inicialice todos los elementos de la array con -1.  

  • Si N ≤ 0 o N ≥ MAX significa que no se puede convertir a M , por lo que devuelve MAX .
  • Si N = M , devuelve 0 cuando N se convirtió en M.
  • De lo contrario, busque el valor en dp[N] si no es -1 , significa que se calculó antes, así que devuelva dp[N] .
  • Si es -1 , llamará a la función recursiva como 2 * N y N – 1 y devolverá el mínimo porque si N es impar, solo se puede alcanzar realizando N – 1 operación y si N es par, entonces 2 * N operaciones deben realizarse, así que compruebe ambas posibilidades y devuelva el mínimo.

A continuación se muestra la implementación del enfoque anterior: 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
const int N = 1e5 + 5;
 
int n, m;
int dp[N];
 
// Function to return the minimum
// number of given operations
// required to convert n to m
int minOperations(int k)
{
    // If k is either 0 or out of range
    // then return max
    if (k <= 0 || k >= 2e4) {
        return 1e9;
    }
 
    // If k = m then conversion is
    // complete so return 0
    if (k == m) {
        return 0;
    }
 
    int& ans = dp[k];
 
    // If it has been calculated earlier
    if (ans != -1) {
        return ans;
    }
    ans = 1e9;
 
    // Call for 2*k and k-1 and return
    // the minimum of them. If k is even
    // then it can be reached by 2*k operations
    // and If k is odd then it can be reached
    // by k-1 operations so try both cases
    // and return the minimum of them
    ans = 1 + min(minOperations(2 * k),
                  minOperations(k - 1));
    return ans;
}
 
// Driver code
int main()
{
    n = 4, m = 6;
    memset(dp, -1, sizeof(dp));
 
    cout << minOperations(n);
 
    return 0;
}

Java

// Java implementation of the approach
import java.util.*;
 
class GFG
{
    static final int N = 10000;
    static int n, m;
    static int[] dp = new int[N];
 
    // Function to return the minimum
    // number of given operations
    // required to convert n to m
    static int minOperations(int k)
    {
 
        // If k is either 0 or out of range
        // then return max
        if (k <= 0 || k >= 10000)
            return 1000000000;
 
        // If k = m then conversion is
        // complete so return 0
        if (k == m)
            return 0;
 
        dp[k] = dp[k];
 
        // If it has been calculated earlier
        if (dp[k] != -1)
            return dp[k];
        dp[k] = 1000000000;
 
        // Call for 2*k and k-1 and return
        // the minimum of them. If k is even
        // then it can be reached by 2*k operations
        // and If k is odd then it can be reached
        // by k-1 operations so try both cases
        // and return the minimum of them
        dp[k] = 1 + Math.min(minOperations(2 * k),
                             minOperations(k - 1));
        return dp[k];
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        n = 4;
        m = 6;
        Arrays.fill(dp, -1);
        System.out.println(minOperations(n));
    }
}
 
// This code is contributed by
// sanjeev2552

Python3

# Python3 implementation of the approach
N = 1000
dp = [-1] * N
 
# Function to return the minimum
# number of given operations
# required to convert n to m
def minOperations(k):
 
    # If k is either 0 or out of range
    # then return max
    if (k <= 0 or k >= 1000):
        return 1e9
     
    # If k = m then conversion is
    # complete so return 0
    if (k == m):
        return 0
     
    dp[k] = dp[k]
     
    # If it has been calculated earlier
    if (dp[k] != -1):
        return dp[k]
     
    dp[k] = 1e9
     
    # Call for 2*k and k-1 and return
    # the minimum of them. If k is even
    # then it can be reached by 2*k operations
    # and If k is odd then it can be reached
    # by k-1 operations so try both cases
    # and return the minimum of them
    dp[k] = 1 + min(minOperations(2 * k),
                    minOperations(k - 1))
    return dp[k]
 
# Driver code
if __name__ == '__main__':
    n = 4
    m = 6
    print(minOperations(n))
     
# This code is contributed by ashutosh450

C#

// C# implementation of the approach
using System;
using System.Linq;
 
class GFG
{
    static int N = 10000;
    static int n, m;
    static int[] dp = Enumerable.Repeat(-1, N).ToArray();
 
    // Function to return the minimum
    // number of given operations
    // required to convert n to m
    static int minOperations(int k)
    {
 
        // If k is either 0 or out of range
        // then return max
        if (k <= 0 || k >= 10000)
            return 1000000000;
 
        // If k = m then conversion is
        // complete so return 0
        if (k == m)
            return 0;
 
        dp[k] = dp[k];
 
        // If it has been calculated earlier
        if (dp[k] != -1)
            return dp[k];
        dp[k] = 1000000000;
 
        // Call for 2*k and k-1 and return
        // the minimum of them. If k is even
        // then it can be reached by 2*k operations
        // and If k is odd then it can be reached
        // by k-1 operations so try both cases
        // and return the minimum of them
        dp[k] = 1 + Math.Min(minOperations(2 * k),
                             minOperations(k - 1));
        return dp[k];
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        n = 4;
        m = 6;
         
        //Arrays.fill(dp, -1);
        Console.Write(minOperations(n));
    }
}
 
// This code is contributed by
// Mohit kumar 29

Javascript

<script>
 
    let N = 10000;
    let n, m;
    let dp = new Array(N);
 
    function minOperations(k)
    {
     
        // If k is either 0 or out of range
        // then return max
        if (k <= 0 || k >= 10000)
            return 1000000000;
   
        // If k = m then conversion is
        // complete so return 0
        if (k == m)
            return 0;
   
        dp[k] = dp[k];
   
        // If it has been calculated earlier
        if (dp[k] != -1)
            return dp[k];
        dp[k] = 1000000000;
   
        // Call for 2*k and k-1 and return
        // the minimum of them. If k is even
        // then it can be reached by 2*k operations
        // and If k is odd then it can be reached
        // by k-1 operations so try both cases
        // and return the minimum of them
        dp[k] = 1 + Math.min(minOperations(2 * k),
                             minOperations(k - 1));
        return dp[k];
    }
     
    // Driver Code
    n = 4;
    m = 6;
    for(let i = 0; i < dp.length; i++)
    {
        dp[i] = -1;
    }
    document.write(minOperations(n));
 
// This code is contributed by unknown2108
</script>
Producción: 

2

 

Publicación traducida automáticamente

Artículo escrito por md1844 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *