d529中等

避開不吉利的四

能在 n 高達 10^18 時,以數位分解計算 1..n 中不含數字 4 的整數個數。

解題思路

n 太大無法枚舉,改成逐位決定。把 n 寫成 d1 d2 ... dL。計算 0..n 中不含 4 的數:考慮「與 n 在前 pos 位相同、第 pos 位第一次比 n 小」的數。這一位可填的允許數字(0~9 去掉 4)且小於 d 的有 smaller(d) 個(d≤4 時為 d 個,d>4 時為 d−1 個),之後 rest 位可自由填 9 種數字,貢獻 smaller(d)·9^rest。

若走到某位 d=4,則「前綴完全貼著 n」的路徑已含 4,不能再繼續,立刻停止,且 n 本身不計入。若所有位都不是 4,則 n 本身合法,要再加 1。這樣把 0..n 分成互不重疊的類別(以第一個與 n 不同的位置分類),因此不重不漏。

計算結果包含 0(0 的十進位也不含 4),而題目只數 1..n,所以最後減 1。答案最大約 9^18 < 2^63,64 位元整數足夠。n=10 時:位置 0 的 d=1,smaller=1,rest=1,加 9;位置 1 的 d=0 貢獻 0;n 本身合法 +1,共 10,扣 0 得 9,與範例一致。

時間 O(log10 n),最多 19 位;空間 O(log n)。

Step-by-step animation

依公開範例追蹤

回報動畫錯誤
步驟 1 / 4

步驟 1:拆成數位

n=10,數位為 1、0。允許數字有 9 個(0~9 去掉 4)。total=0。

1
0
total
0
has4
否

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int smaller(int d) { return d - (d > 4 ? 1 : 0); }

int main() {
    string s;
    cin >> s;
    int len = s.size();
    vector<ll> pw(len + 1, 1);
    for (int i = 1; i <= len; i++) pw[i] = pw[i - 1] * 9;
    ll total = 0;
    bool has4 = false;
    for (int pos = 0; pos < len; pos++) {
        int d = s[pos] - '0';
        int rest = len - pos - 1;
        total += smaller(d) * pw[rest];
        if (d == 4) { has4 = true; break; }
    }
    if (!has4) total++;
    cout << total - 1 << '\n';
    return 0;
}

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

更多