Mancunian and K-Reachability

4

6 votes
Mathematics, Easy-Medium, Mathematics, Mathamatics
Problem

An integer is said to be k-reachable from another integer if the latter can be converted to the former by replacing atmost k digits. Note that, leading 0's are not considered the part of the number and hence are not allowed to replaced with non-zero integers.

For example,

1123 is 15-reachable from 2223 but not 1-reachable.

6 is 2-reachable from 10, but 10 is not 2-reachable from 6

Mancunian has been given the following problem. He is provided the initial integer N and the value of k. Now he has to answer Q queries. Each query is represented by a pair (L, R). The answer for a query is the number of integers in the range L to R (inclusive) which are k-reachable from N.

Input:
The first line contains three integers N, k and Q.
Each of the next Q lines is of the form L R denoting a specific query.

Output:
For each query, output the answer to the given query in a new line.

Constraints:
1 <= N < 107
1 <= k <= 5
1 <= Q <= 105
1 <= L <= R < 107

Sample Input
6 2 1
8 12
Sample Output
2
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

8 and 9 are 2-reachable from 6 whereas 10, 11 and 12 are not reachable at all.

Editor Image

?