跳到正文

题解

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

hwq202314约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年10月14日
收录
2026年10月19日
更新
2026年11月14日
篇幅
约 3 分钟

版本

  1. v1当前

Link

简单题。

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

题目简述

给定 ll 和 rr,求出下式的值:

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

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

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

C++
1 2 2 4 4 4 4 8 8 8 8 8 8 8 8 16 16 16 16 16

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

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

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

AC 代码
C++
#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;
}
原文