1. 程式人生 > 其它 >【AcWing】第6場周賽 B題 3734. 求和 (思維)

【AcWing】第6場周賽 B題 3734. 求和 (思維)

AcWing 3734. 求和

其實這道題並不難,只是思維性很強!

因為 \(a\) 的各個數位不包含除了 \(4\)\(7\)​ 以外的其他數字。

仔細觀察資料會發現因為 \(1\le l \le r\le 10^9\) 中符合條件的其實不會很多,

所以可以選擇 DFS 打表把所有符合條件的枚舉出來

詳細見程式碼理解

ll l, r;
vector<ll> a;
void dfs(int u, ll x) {
    a.push_back(x);
    if (u == 10) return;
    dfs(u + 1, x * 10 + 4);
    dfs(u + 1, x * 10 + 7);
}
int main() {
    cin.tie(nullptr)->sync_with_stdio(false);
    cin >> l >> r;
    dfs(0, 0);
    sort(a.begin(), a.end());
    ll d = lower_bound(a.begin(), a.end(), l) - a.begin();
    ll c = lower_bound(a.begin(), a.end(), r) - a.begin();
    ll sum = 0;
    if (d != c) { // 分段
        sum += a[d] * (a[d] - l + 1);
        for (int i = d + 1; i < c; ++i) sum += a[i] * (a[i] - a[i - 1]);
        if (c - 1 >= d) sum += a[c] * (r - a[c - 1]);
        cout << sum;
    } else
        cout << a[d] * (r - l + 1);
}

The desire of his soul is the prophecy of his fate
你靈魂的慾望,是你命運的先知。