daiict's blog

By daiict, history, 8 years ago, In English

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.

Tags #dp
  • Vote: I like it
  • +8
  • Vote: I do not like it

| Write comment?
»
8 years ago, # |
  Vote: I like it +10 Vote: I do not like it

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 years ago, # |
  Vote: I like it +1 Vote: I do not like it

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

»
8 years ago, # |
  Vote: I like it +1 Vote: I do not like it

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 years ago, # |
  Vote: I like it 0 Vote: I do not like it

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 years ago, # ^ |
      Vote: I like it +12 Vote: I do not like it

    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] ]