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

Автор randomrandom1810, история, 4 года назад, По-английски

We are provided with 2 integers, F and K and we want to find an integer N such that

  • N is divisible by F
  • N is a number whose sum of digits is an integer K

return minimum N satisfying the 2 conditions.

constraints

1 <= F <= 495

1 <= K <= 5000

Please tell me how to approach this problem.

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

»
4 года назад, скрыть # |
 
Проголосовать: нравится +20 Проголосовать: не нравится

A brief approach :
$$$dp[i][j]$$$ denotes the minimum length of the number satisfying the given constraints, where $$$i$$$ denotes the remaining sum of the digits of the number, $$$j$$$ denotes the remainder when divided by $$$F$$$.
Transitions are simple : Assume you add digit $$$x$$$ in the current state $$$dp[i][j]$$$, then you will get $$$dp[i-x]$$$$$$[$$$$$$(j*10 + x)mod F]$$$and you have to take the $$$min$$$ of all the $$$10$$$ possibilities of digits.
Now, you have the $$$min$$$ length of the final answer, you can easily trace back the $$$dp$$$ values to get the final string (or number).

Time Complexity : $$$O(F*K)$$$

»
4 года назад, скрыть # |
Rev. 8  
Проголосовать: нравится +3 Проголосовать: не нравится

Let $$$dp[i][j]$$$ denote the min. no of digits a number can have such that it has sum of digits equals $$$i$$$ and gives remainder $$$j$$$ when divided by $$$F$$$.

Transitions can be done easily via forward-style DP. Once you know $$$dp[i][j]$$$ (say, its value is $$$x$$$), then if your $$$(x+1)$$$th digit is $$$z$$$, then $$$dp[i+z][(j + z*{10}^{x})\,mod F] \lt --min(dp[i+z][(j + z*{10}^{x})\,mod F],dp[i][j]+1)$$$

To built the number, start placing the leftmost digit $$$j$$$, such that it satisfies $$$dp[k-j][(-{10}^{dp[k][0]})\,mod\,F]$$$ is minimum, and repeat the process for remaining digits.

  • »
    »
    4 года назад, скрыть # ^ |
     
    Проголосовать: нравится 0 Проголосовать: не нравится

    Please correct me if I am wrong, I don't see how this works if the digit we are adding to the front i.e. z is 0

    $$$dp[i + 0][j + 0] := min(dp[i + 0][j + 0], dp[i][j] + 1)$$$

    A trivial example can be F=101, K=2 N should be 101

»
4 года назад, скрыть # |
Rev. 2  
Проголосовать: нравится +14 Проголосовать: не нравится
»
4 года назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

My solution finds the minimum length of number which satisfies both the conditions.

Here is my recursive DP code

I am unable to print the answer through DP table , Anyone pls Help :)