a658困難逐位高低段分析與零的前導修正

CPE:The Counting Problem (UVa 1640)

在 O(log b) 時間計算整段數字出現次數。

前往題目練習 →回報教學錯誤每筆時間 O(10 log b),空間 O(10)。

解題思路

先定義 F(x) 為 1 到 x 的十個數字計數。枚舉位值 p=1,10,100,…,拆出 high=x//(10p)、cur=x//p%10、low=x%p。對非零數字 d,每個完整循環提供 high·p 次;cur>d 再加 p,cur=d 再加 low+1。這等於依高位分組,計算目前位能固定為 d 的數量。

0 不可當前導位,所以 high>0 時基底改為 (high−1)p,然後依 cur 是否為 0 補 low+1 或 p;high=0 的這一位完全不貢獻 0。先排序端點,再輸出 F(b)−F(a−1)。輸入正數範圍不含整數 0,0 0 是終止標記。

Step-by-step animation

示意:統計 1 到 13

回報動畫錯誤
步驟 1 / 3

個位

high=1,cur=3,low=0;個位的 1 出現於 1、11。

p=1
high=1
cur=3
low=0
個位1
2
個位0
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <array>
#include <algorithm>
using namespace std;
array<long long, 10> count_digits(long long x) {
    array<long long, 10> a{};
    for (long long p = 1; p <= x; p *= 10) {
        long long h = x / (p * 10), c = x / p % 10, l = x % p;
        for (int d = 1; d <= 9; d++)
            a[d] += h * p + (c > d ? p : (c == d ? l + 1 : 0));
        if (h)
            a[0] += (h - 1) * p + (c == 0 ? l + 1 : p);
    }
    return a;
}
int main() {
    long long a, b;
    while (cin >> a >> b && (a || b)) {
        if (a > b)
            swap(a, b);
        auto r = count_digits(b), l = count_digits(a - 1);
        for (int d = 0; d < 10; d++)
            cout << (d ? " " : "") << r[d] - l[d];
        cout << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多