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 Ruby (2.3.3) (judge verdict: Accepted)

# 桁DP

n = gets.chomp.split("").map(&:to_i)
k = gets.to_i
length = n.length
# dp[上から i 桁まで][smaller][0 でない数字を使った回数]の出現回数
dp = (length + 1).times.map { 2.times.map { Array.new([length + 1, k + 1].max, 0) } }
# 初期化
# dp[0 桁目まで][桁は不自由][0 でない数字 を 0 回使った]の出現回数は 1 
dp[0][0][0] = 1

# 桁数分ループする（i は遷移元の桁）
length.times do |i|
  # smaller == 1 の場合、以下の桁は自由
  2.times do |smaller|
    # 1 を使った回数ごとに確認する
    length.times do |count|
      # smaller が既に 1 の場合は 10 回ループ、0 の場合は(その桁の数字 + 1）回ループ
      limit = smaller == 1 ? 9 : n[i]
      (limit + 1).times do |d|
        # smaller == 0 且つ d == limit（上限）の時のみ、0 のまま遷移する
        next_smaller = smaller == 0 && d == limit ? 0 : 1
        # d == 0 でない場合は回数を足す
        addition = d == 0 ? 0 : 1
        # 次の桁に遷移する
        dp[i + 1][next_smaller][count + addition] += dp[i][smaller][count]
      end
    end
  end
end

ans = 0
# 桁が自由、不自由ともに、(0 以外を k 回使った出現回数)を ans に足す
2.times do |i|
  ans += dp[length][i][k]
end
puts ans