【AcWing】第6场周赛 B题 3734. 求和 (思维)

AcWing 3734. 求和

其实这道题并不难,只是思维性很强!

因为 (a) 的各个数位不包含除了 (4)(7)​ 以外的其他数字。

仔细观察数据会发现因为 (1le l le rle 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
你灵魂的欲望,是你命运的先知。

原文地址:https://www.cnblogs.com/RioTian/p/15134429.html