Número mínimo de palíndromos necesarios para expresar N como suma | Serie 1

Dado un número N, tenemos que encontrar el número mínimo de palíndromos necesarios para expresar N como suma de ellos. 
Ejemplos:
 

Entrada: N = 11 
Salida:
11 es en sí mismo un palíndromo.
Entrada: N = 65 
Salida:
65 se puede expresar como la suma de tres palíndromos (55, 9, 1).

Enfoque: 
Podemos usar Programación Dinámica para resolver este problema. La idea es generar primero todos los palíndromos hasta N ordenados, y luego podemos tratar este problema como una variación del problema de suma de subconjuntos , donde tenemos que encontrar el tamaño del subconjunto más pequeño tal que su suma sea N A
continuación se muestra la implementación del enfoque anterior: 
 

CPP

// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
 
// Declaring the DP table as global variable
vector<vector<long long> > dp;
 
 
// A utility for creating palindrome
int createPalindrome(int input, bool isOdd)
{
    int n = input;
    int palin = input;
 
    // checks if number of digits is odd or even
    // if odd then neglect the last digit of input in
    // finding reverse as in case of odd number of
    // digits middle element occur once
    if (isOdd)
        n /= 10;
 
    // Creates palindrome by just appending reverse
    // of number to itself
    while (n > 0) {
        palin = palin * 10 + (n % 10);
        n /= 10;
    }
 
    return palin;
}
 
// Function to generate palindromes
vector<int> generatePalindromes(int N)
{
    vector<int> palindromes;
    int number;
 
    // Run two times for odd and even length palindromes
    for (int j = 0; j < 2; j++) {
        // Creates palindrome numbers with first half as i.
        // Value of j decides whether we need an odd length
        // or even length palindrome.
        int i = 1;
        while ((number = createPalindrome(i++, j)) <= N)
            palindromes.push_back(number);
    }
 
    return palindromes;
}
 
// Function to find the minimum
// number of elements in a sorted
// array A[i..j] such that their sum is N
long long minimumSubsetSize(vector<int>& A, int i, int j, int N)
{
    if (!N)
        return 0;
 
    if (i > j || A[i] > N)
        return INT_MAX;
 
    if (dp[i][N])
        return dp[i][N];
 
    dp[i][N] = min(1 + minimumSubsetSize(A, i + 1, j,
                                         N - A[i]),
                   minimumSubsetSize(A, i + 1, j, N));
 
    return dp[i][N];
}
 
// Function to find the minimum
// number of palindromes that N
// can be expressed as a sum of
int minimumNoOfPalindromes(int N)
{
    // Getting the list of all palindromes upto N
    vector<int> palindromes = generatePalindromes(N);
 
    // Sorting the list of palindromes
    sort(palindromes.begin(), palindromes.end());
 
    // Initializing the DP table
    dp = vector<vector<long long> >(palindromes.size(),
                                    vector<long long>(N + 1, 0));
 
    // Returning the required value
    return minimumSubsetSize(palindromes, 0,
                             palindromes.size() - 1, N);
}
 
// Driver code
int main()
{
    int N = 65;
    cout << minimumNoOfPalindromes(N);
    return 0;
}

Java

/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
 
class GFG {
  // Java implementation of above approach
 
  // Declaring the DP table as global variable
  static long[][] dp;
 
 
  // A utility for creating palindrome
  static int createPalindrome(int input, int isOdd)
  {
    int n = input;
    int palin = input;
 
    // checks if number of digits is odd or even
    // if odd then neglect the last digit of input in
    // finding reverse as in case of odd number of
    // digits middle element occur once
    if (isOdd > 0)
      n /= 10;
 
    // Creates palindrome by just appending reverse
    // of number to itself
    while (n > 0) {
      palin = palin * 10 + (n % 10);
      n /= 10;
    }
 
    return palin;
  }
 
  // Function to generate palindromes
  static ArrayList<Integer> generatePalindromes(int N)
  {
    ArrayList<Integer> palindromes = new ArrayList<>();
    int number;
 
    // Run two times for odd and even length palindromes
    for (int j = 0; j < 2; j++) {
      // Creates palindrome numbers with first half as i.
      // Value of j decides whether we need an odd length
      // or even length palindrome.
      int i = 1;
      while ((number = createPalindrome(i++, j)) <= N)
        palindromes.add(number);
    }
 
    return palindromes;
  }
 
  // Function to find the minimum
  // number of elements in a sorted
  // array A[i..j] such that their sum is N
  static long minimumSubsetSize(ArrayList<Integer> A, int i, int j, int N)
  {
    if (N == 0)
      return 0;
 
    if (i > j || A.get(i) > N)
      return Integer.MAX_VALUE;
 
    if (dp[i][N] > 0)
      return dp[i][N];
 
    dp[i][N] = Math.min(1 + minimumSubsetSize(A, i + 1, j,
                                              N - A.get(i)),
                        minimumSubsetSize(A, i + 1, j, N));
 
    return dp[i][N];
  }
 
  // Function to find the minimum
  // number of palindromes that N
  // can be expressed as a sum of
  static int minimumNoOfPalindromes(int N)
  {
    // Getting the list of all palindromes upto N
    ArrayList<Integer> palindromes = generatePalindromes(N);
 
    // Sorting the list of palindromes
    Collections.sort(palindromes);
 
    // Initializing the DP table
    dp = new long [palindromes.size()][N + 1];
 
 
 
    // Returning the required value
    return (int)minimumSubsetSize(palindromes, 0,
                                  palindromes.size() - 1, N);
  }
 
  // Driver Code
  public static void main(String args[])
  {
    int N = 65;
    System.out.println(minimumNoOfPalindromes(N));
  }
}
 
// This code is contributed by shinjanpatra.

Python3

# Python3 implementation of above approach
 
# Declaring the DP table as global variable
dp = [[0 for i in range(1000)] for i in range(1000)]
 
# A utility for creating palindrome
def createPalindrome(input, isOdd):
 
    n = input
    palin = input
 
    # checks if number of digits is odd or even
    # if odd then neglect the last digit of input in
    # finding reverse as in case of odd number of
    # digits middle element occur once
    if (isOdd):
        n //= 10
 
    # Creates palindrome by just appending reverse
    # of number to itself
    while (n > 0):
        palin = palin * 10 + (n % 10)
        n //= 10
 
    return palin
 
# Function to generate palindromes
def generatePalindromes(N):
 
    palindromes = []
    number = 0
 
    # Run two times for odd and even length palindromes
    for j in range(2):
         
        # Creates palindrome numbers with first half as i.
        # Value of j decides whether we need an odd length
        # or even length palindrome.
        i = 1
        number = createPalindrome(i, j)
        while number <= N:
            number = createPalindrome(i, j)
            palindromes.append(number)
            i += 1
 
    return palindromes
 
# Function to find the minimum
# number of elements in a sorted
# array A[i..j] such that their sum is N
def minimumSubsetSize(A, i, j, N):
 
    if (not N):
        return 0
 
    if (i > j or A[i] > N):
        return 10**9
 
    if (dp[i][N]):
        return dp[i][N]
 
    dp[i][N] = min(1 + minimumSubsetSize(A, i + 1, j, N - A[i]),
                    minimumSubsetSize(A, i + 1, j, N))
 
    return dp[i][N]
 
# Function to find the minimum
# number of palindromes that N
# can be expressed as a sum of
def minimumNoOfPalindromes(N):
 
    # Getting the list of all palindromes upto N
    palindromes = generatePalindromes(N)
 
    # Sorting the list of palindromes
    palindromes = sorted(palindromes)
 
    # Returning the required value
    return minimumSubsetSize(palindromes, 0, len(palindromes) - 1, N)
 
# Driver code
N = 65
print(minimumNoOfPalindromes(N))
 
# This code is contributed by mohit kumar 29

Javascript

<script>
 
// JavaScript implementation of above approach
 
// Declaring the DP table as global variable
let dp = new Array(1000);
for(let i = 0; i < 1000; i++)
{
    dp[i] = new Array(1000).fill(0);
}
 
// A utility for creating palindrome
function createPalindrome(input, isOdd){
 
    let n = input
    let palin = input
 
    // checks if number of digits is odd or even
    // if odd then neglect the last digit of input in
    // finding reverse as in case of odd number of
    // digits middle element occur once
    if (isOdd)
        n = Math.floor(n /10)
 
    // Creates palindrome by just pushing reverse
    // of number to itself
    while (n > 0){
        palin = palin * 10 + (n % 10)
        n = Math.floor(n /10)
    }
 
    return palin
}
 
// Function to generate palindromes
function generatePalindromes(N){
 
    let palindromes = []
    let number = 0
 
    // Run two times for odd and even length palindromes
    for(let j = 0; j < 2; j++)
    {
         
        // Creates palindrome numbers with first half as i.
        // Value of j decides whether we need an odd length
        // or even length palindrome.
        let i = 1
        number = createPalindrome(i, j)
        while(number <= N){
            number = createPalindrome(i, j)
            palindromes.push(number)
            i += 1
        }
    }
 
    return palindromes
}
 
// Function to find the minimum
// number of elements in a sorted
// array A[i..j] such that their sum is N
function minimumSubsetSize(A, i, j, N){
 
    if (N == 0)
        return 0
 
    if (i > j || A[i] > N)
        return Math.pow(10,9)
 
    if (dp[i][N])
        return dp[i][N]
 
    dp[i][N] = Math.min(1 + minimumSubsetSize(A, i + 1, j, N - A[i]),
                    minimumSubsetSize(A, i + 1, j, N))
 
    return dp[i][N]
}
 
// Function to find the minimum
// number of palindromes that N
// can be expressed as a sum of
function minimumNoOfPalindromes(N){
 
    // Getting the list of all palindromes upto N
    let palindromes = generatePalindromes(N)
 
    // Sorting the list of palindromes
    palindromes.sort((a,b)=>a-b)
 
    // Returning the required value
    return minimumSubsetSize(palindromes, 0, palindromes.length - 1, N)
}
 
// Driver code
let N = 65
document.write(minimumNoOfPalindromes(N),"</br>")
 
// This code is contributed by shinjanpatra
 
</script>
Producción: 

3

 

Publicación traducida automáticamente

Artículo escrito por vaibhav29498 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 *