题解:2026/10/14 模拟赛 T1 mahou

· · 题解

Link

简单题。

虽然出题人说是原创题,但我感觉这题好像之前做过。

::::info[题目简述]

给定 l 和 r,求出下式的值:

\sum_{i = l}^{r} \operatorname{highbit}(i)

其中 \operatorname{highbit}(i) 表示 i 的二进制表示下最高位 1 的权值。

::::

遇事不决先打表。下面是 1 \sim 20 的 \operatorname{highbit}(i) 的值:

1 2 2 4 4 4 4 8 8 8 8 8 8 8 8 16 16 16 16 16

然后就会发现每个值的个数和值相同。

那就很简单了,直接分别求 [1,l] 和 [1, r],到时候答案减一下就出来了。注意及时取模。

时间复杂度 O(\operatorname{log}(n))。

::::success[AC 代码]

#include <iostream>

namespace Qwarth {

using i64 = long long;

const i64 mod = 998244353;

i64 f(i64 x) {
    i64 a = 1, res = 0;
    while (x >= (a << 1LL)) {
        res = (res + (a % mod) * (a % mod) % mod) % mod;
        a <<= 1LL;
    }
    res = (res + (a % mod) * ((x - a + 1) % mod) % mod) % mod;
    return res;
}

void main() {
    i64 l, r;
    std::cin >> l >> r;
    std::cout << (f(r) - f(l - 1) + mod) % mod << '\n';
}
}  // namespace Qwarth

int main() {
    freopen("mahou.in", "r", stdin);
    freopen("mahou.out", "w", stdout);
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    // for (int i = 1; i <= 20; ++i) {
        // std::cerr << Qwarth::f(i) << '\n';
    // }
    int _T = 1;
    std::cin >> _T;
    while (_T--) {
        Qwarth::main();
    }
    return 0;
}

::::