Skip to content

[ZJOI2010] 数字计数 ​

题目描述 ​

给定两个正整数 a 和 b,求在 [a,b] 中的所有整数中,每个数码(digit)各出现了多少次。

输入格式 ​

仅包含一行两个整数 a,b,含义如上所述。

输出格式 ​

包含一行十个整数,分别表示 0∼9 在 [a,b] 中出现了多少次。

样例 #1 ​

样例输入 #1 ​

1 99

样例输出 #1 ​

9 20 20 20 20 20 20 20 20 20

提示 ​

数据规模与约定 ​

  • 对于 30% 的数据,保证 a≤b≤106;
  • 对于 100% 的数据,保证 1≤a≤b≤1012。

题解 ​

c++
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<cstring>
#include<cmath>
#include<set>
#include<map>

using namespace std;
#define ll long long
#define ull unsigned long long
#define endl '\n'
const int N = 15;
const int mod = 1e9 + 7;
const ll inf = 1e18;
int dir[4][2] = {-1, 0, 0, 1, 1, 0, 0, -1}; //  上右下左
ll ans1[N], ans2[N], dp[N], cnt[N];

void resolve(ll x,ll *ans) {
    vector<int> a(N);
    int len = 0;
    while (x) {
        a[++len] = x % 10;
        x /= 10;
    }
    for (int i = len; i >= 1; i--) {
        for (int j = 0; j <= 9; j++) {//  不考虑首位的情况
            ans[j] += dp[i - 1] * a[i];//  统计每个数字出现的次数
        }
        for (int j = 0; j < a[i]; j++) {//  小于
            ans[j] += cnt[i - 1];//
        }
        ll n2 = 0;
        for (int j = i - 1; j >= 1; j--) {//  第i位还出现了后面位数的次数
            n2 = n2 * 10 + a[j];
        }
        ans[a[i]] += n2 + 1;
        ans[0] -= cnt[i - 1];//  dp[0]算上了前导零需要减去
    }
}

void solve() {
    ll l, r;
    cin >> l >> r;
    cnt[0] = 1;
    for (int i = 1; i <= 15; i++) {
        dp[i] = dp[i - 1] * 10 + cnt[i - 1]; //  dp[i]表示有i位数字,每个数字有多少个(包括前导零)
        cnt[i] = 10 * cnt[i - 1];
    }
    resolve(l - 1, ans1);
    resolve(r, ans2);
    for (int i = 0; i <= 9; i++) {
        cout << ans2[i] - ans1[i] << ' ';
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int _ = 1;
    //cin >> _;
    while (_--)
        solve();
    return 0;
}