Olympiad in Informatics

[AtCoder Regular Contest 090F] Number of Digits — Solution

Main Idea

This problem is pretty interesting.

First there's a brute force: for \(l\) within \(10^7\) you can just do two-pointers; if it's above \(10^7\), you notice that \(f(r) - f(l) \leq 1\). Then we can consider enumerating the length of this contiguous segment, \(L = x + y\), where \(x\) is the part with \(i\) \(0\)s and \(y\) is the part with \(i + 1\) \(0\)s. There's an equation: \(x \times i + y \times (i + 1) = (x + y)i + y = Li + y = S\). So when enumerating \(L\), if \(S \bmod L \equiv 0\), that means \(y = 0\), and you count the left endpoints within \(10^i\) (it's really just subtracting an extra \(L - 1\)). If \(S \bmod L \neq 0\), that means \(x, y\) are determined, so you just ++.

Code

// ARC090F.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 5e7 + 200, mod = 1e9 + 7;

int n, f[MAX_N];

int fpow(int bas, int tim)
{
    int ret = 1;
    while (tim)
    {
        if (tim & 1)
            ret = 1LL * ret * bas % mod;
        bas = 1LL * bas * bas % mod;
        tim >>= 1;
    }
    return ret;
}

int main()
{
    scanf("%d", &n);
    for (int i = 1; i < MAX_N; i++)
        f[i] = f[i / 10] + 1;
    int ans = 0;
    for (int i = 1, j = 1, sum = 0; i < 1e7; i++)
    {
        while (sum < n)
            sum += f[j++];
        if (sum == n)
            ans++;
        sum -= f[i];
    }
    for (int i = 1; i <= n / 8; i++)
    {
        if (n % i == 0)
            // y == 0, t = n / i;
            ans = (0LL + ans + (0LL + fpow(10, n / i) + mod - (fpow(10, (n / i) - 1) + i - 1) % mod) % mod) % mod;
        else
            ans = (0LL + ans + 1) % mod;
    }
    printf("%d\n", ans);
    return 0;
}