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

Автор daiict, история, 8 лет назад, По-английски

Can anyone help me in dp problem. problem statement is as following. Find how many numbers of length n are there such that each number is at least 4 smaller/greater than the number before and after it.

E.g. if n = 5, such numbers are 39518, 15951, etc.

Теги #dp
  • Проголосовать: нравится
  • +8
  • Проголосовать: не нравится

»
8 лет назад, # |
  Проголосовать: нравится +10 Проголосовать: не нравится

Let dp[a][b] be the number of numbers with length a that end in the digit b (a ranges from 1 to n, and b ranges from 0 to 9). Then dp[1][b] = 1 for all b. For a > 1 and a fixed value of b, initialize it to zero. Then, loop over all possible values of the second to last digit b', and if |b — b'| >= 4, add dp[a-1][b'] to dp[a][b].

»
8 лет назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится

I am not able to understand the problem, can you please post the problem link or elaborate here. Thanks.

»
8 лет назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится

I do not have the problem link.So I am elaborating the question. You have to answer the possible ways of n digit number such that the next digit has absolute difference of at least 4 than the previous digit.

»
8 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

An implementation based on mkirsche's comment with O(nm) where m is number of 2-digit numbers with digits having absolute difference >= 4, which is 42

Code

  • »
    »
    8 лет назад, # ^ |
      Проголосовать: нравится +12 Проголосовать: не нравится

    It could also be done better with complexity O(log n) using matrix exponentiation.

    The result would be sum of all elements in the matrix Z. where Z = A ^ (n — 1)

    and A = [

    [ 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

    [ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]

    [ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]

    [ 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]

    [ 1, 0, 0, 0, 0, 0, 0, 0, 1, 1]

    [ 1, 1, 0, 0, 0, 0, 0, 0, 0, 1]

    [ 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]

    [ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]

    [ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]

    [ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0] ]