Table of Contents

ExplanationImplementation

Official Analysis (C++)

Explanation

First, to reduce our problem, we observe the following:

  1. Being divisible by MM means that our number is equivalent to 00, mod MM.
  2. Let count_magic(x)\texttt{count\_magic}(x) define all the magic numbers x\leq x. The frequency of magic numbers in the range [a,b][a, b] is count_magic(b)count_magic(a1)\texttt{count\_magic}(b) - \texttt{count\_magic}(a - 1).

Then, we can use a somewhat typical DP state to model the problem.

Let dp[i][j][k]\texttt{dp}[i][j][k] represent all the possibilities, when:

  • We have considered the first ii digits
  • Our number is equivalent to jj, mod MM
  • kk represents if our number is "free" or not
    • If the first ii 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 00 mod MM.

Here are some key points to consider when implementing the problem:

  • Handling a1a-1 in string form is annoying. Instead, we can consider the values of count_magic(a)\texttt{count\_magic}(a) and count_magic(b)\texttt{count\_magic}(b), then manually handle aa on its own.
  • Note how the problem guarantees that aa and bb are the same length. This means that we can effectively ignore leading zeroes in our implementation.

Implementation

Time Complexity: O(MD)\mathcal{O}(M \cdot D), where DD is the number of digits in aa and bb.

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!