Editorial for COCI '07 Contest 3 #5 Cudak
Submitting an official solution before solving the problem yourself is a bannable offence.
We will describe two ways to approach the problem.
The "classic" approach is to develop the function how many integers less than or equal to have the digit-sum . The solution is then .
To calculate the value of , we use an auxiliary function how many integers of length have the digit-sum . The function is easy to calculate using dynamic programming.
Suppose is digits long and its first digit is . Then . This can be calculated iteratively.
An alternative approach is to recursively build the number and take advantage of many subproblems sharing the same solution. Suppose that, in our recursive function, we have decided on a prefix of the number. Then we know exactly what range of numbers can be built hereafter: if we put more zeros, we get . If we put nines, we get .
If this entire range is outside the interval , then we return . If the entire range is inside the interval, then the solution is equivalent to calculating the function from above (this is where many subproblems share the same solution). If the range is partially inside , then we just continue the recursion (try every digit). The key is to notice that this last case will happen only times, so this solution will be as efficient as the first one. The accompanying source code demonstrates the second approach in a single function.
We can find the smallest integer with the digit-sum while calculating the total number of integers.
An alternative is to use binary search to find the first number such that the interval contains exactly one integer with the digit-sum (this is equivalent to the first half of the problem).
Comments