📜  门| GATE CS 2021 |设置 2 |问题 8(1)

📅  最后修改于: 2023-12-03 15:28:39.173000             🧑  作者: Mango

GATE CS 2021 Set 2 Problem 8

This is a programming problem from the GATE CS 2021 Set 2. The problem involves writing code to find the minimum cost required to form a number by appending digits to the given number.

Problem Description

Given a string num representing a non-negative integer, and an integer k, you need to find the minimum cost required to form a number of length k by appending digits from the original number. The cost of appending a digit at the i-th position is equal to the value of i modulo 10. For example, the cost of appending a digit at index 0 is 0, the cost of appending a digit at index 1 is 1, the cost of appending a digit at index 2 is 2, and so on.

Input

The input consists of two integers num and k separated by a space. num represents the non-negative integer, and k represents the length of the number that needs to be formed.

Output

The output consists of a single integer denoting the minimum cost required to form the number by appending digits from the given number.

Example

Input:

num = "1234", k = 5

Output:

10
Approach

To solve this problem, we can use dynamic programming. We can define a dp array of size k+1 to store the minimum cost required to form a number of length i by appending digits from the given number.

dp[i] = min(dp[i], dp[i-j] + (i-j)%10)

The dp[i-j] represents the minimum cost required to form a number of length i-j by appending digits from the given number. The (i-j)%10 represents the cost of appending a digit at the i-th position. We need to iterate from j=1 to j<=min(i,k) to consider all possible prefixes of length j that can be appended to form a number of length i.

Complexity Analysis

The time complexity of the solution is O(k^2) as we need to calculate the minimum cost for all possible lengths of the number. The space complexity of the solution is O(k) as we need to store the minimum cost for all possible lengths of the number in the dp array.

Code
def min_cost(num: str, k: int) -> int:
    n = len(num)
    dp = [0] + [float('inf')] * k
    for i in range(1, k+1):
        for j in range(1, min(i, n)+1):
            dp[i] = min(dp[i], dp[i-j] + (i-j)%10)
    return dp[k]