Explanation
First, to reduce our problem, we observe the following:
- Being divisible by means that our number is equivalent to , mod .
- Let define all the magic numbers . The frequency of magic numbers in the range is .
Then, we can use a somewhat typical DP state to model the problem.
Let represent all the possibilities, when:
- We have considered the first digits
- Our number is equivalent to , mod
- represents if our number is "free" or not
- If the first digits in our number match up with the bound or not
Then, after considering all of our digits, we consider all the numbers equivalent to mod .
Here are some key points to consider when implementing the problem:
- Handling in string form is annoying. Instead, we can consider the values of and , then manually handle on its own.
- Note how the problem guarantees that and are the same length. This means that we can effectively ignore leading zeroes in our implementation.
Implementation
Time Complexity: , where is the number of digits in and .
C++
#include <bits/stdc++.h>using namespace std;constexpr int MOD = 1e9 + 7;int count_magic(int m, int d, string bound, bool ok) {if (bound.length() == 1) {int num_good = 0;int cur_digit = bound[0] - '0';for (int i = 0; i < cur_digit; i++) { num_good += (i != d) && (i % m == 0); }
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!