Official

C - Repunit Trio Editorial by en_translator


See also another solution by evima, which is simpler.

An integer can be represented as the sum of exactly three repunits if and only if:

  • all the digits are between \(1\) and \(3\), inclusive, and are monotonically increasing from the most significant to the least
  • the least significant digit (ones place) is \(3\).

Thus, a conforming integer consists of zero or more \(1\)s, zero or more \(2\)s, and one or more \(3\)s.

One can use this property to perform a exhaustive search. It is sufficient to enumerate the number of \(1\)s, the number of \(2\)s, and the number of \(3\)s. Under the constraints of \(N\) in this problem, it is sufficient to enumerate up to \(12\) digits. (This bound can be found by inspecting the sample, searching randomly, or evaluating mathematically.)

With a little ingenious on the exhaustive search, the problem could be solved in \(\mathrm{O}(N)\) time; while this time, enumerating all the candidates and sorting them to find the \(N\)-th one, which costs \(\mathrm{O}(N\log N)\) time, is still fast enough.

Sample code (C++):

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  for(int d = 1; d <= 12; d++) {
    for(int a = d - 1; a >= 0; a--) {
      for(int b = d - a - 1; b >= 0; b--) {
        int c = d - a - b;
        if(--n == 0) {
          cout << string(a, '1') + string(b, '2') + string(c, '3') << endl;
          return 0;
        }
      }
    }
  }
}

posted:
last update: