Problem:
Score : 500 points

Problem Statement

Find the number of integers between 1 and N (inclusive) that contains exactly K non-zero digits when written in base ten.

Constraints

1 \leq N < 10^{100}

1 \leq K \leq 3

Input

Input is given from Standard Input in the following format:

N
K

Output

Print the count.

Sample Input 1

100
1

Sample Output 1

19

The following 19 integers satisfy the condition:

1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100

Sample Input 2

25
2

Sample Output 2

14

The following 14 integers satisfy the condition:

11,12,13,14,15,16,17,18,19,21,22,23,24,25

Sample Input 3

314159
2

Sample Output 3

937

Sample Input 4

9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
3

Sample Output 4

117879300

Solution in Scala (2.11.7) (judge verdict: Accepted)

object Main {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)

    val N = sc.nextLine()
    val L = N.length
    val K = sc.nextInt()

    println(bitDp(N, K, L))
  }

  def bitDp(S: String, K: Int, L: Int): Long = {
    val dp = Array.fill(L+1, 2, 5)(0L)

    dp(0)(0)(0) = 1
    for {
      i <- 0 until L
      d = S.charAt(i) - '0'
      f <- 0 until 2 // N未満が確定している => 1
      n <- 0 to (if (f == 1) 9 else d)
    } if (f == 1 || n < d) {
      if (n != 0) {
        for (j <- 1 until 5)
          dp(i+1)(1)(j) += dp(i)(f)(j-1)
      } else {
        for (j <- 0 until 5)
          dp(i+1)(1)(j) += dp(i)(f)(j)
      }
    } else {
      if (n != 0) {
        for (j <- 1 until 5)
          dp(i+1)(0)(j) += dp(i)(f)(j-1)
      } else {
        for (j <- 0 until 5)
          dp(i+1)(0)(j) += dp(i)(f)(j)
      }
    }

    dp(L)(0)(K) + dp(L)(1)(K)
  }

}