跳到正文

题解

题解:P11397 界分数

PrinceEvan约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
获赞
1
题目
P11397

版本

  1. v1当前

这是本蒟蒻第一次写题解。

先看数据范围:1≤n≤10181\le n \le 10^{18}, 一看就要找规律!

直接开始打标找 f(i)f(i) 的规律。

ii11223344556677889910101111121213131414151516161717181819192020
f(i)f(i)1122333344444444555555555555555566666666

可以发现从 f(2)f(2) 开始每个数字出现的次数为 1、2、4、8、16...1、2、4、8、16...

于是题目就变成了求 1+2+2+3+3+3+3+4+4+4+4+4+4+4+4......1+2+2+3+3+3+3+4+4+4+4+4+4+4+4...... 这个序列前 n−1n-1 的项和在加 nn。

因为 nn 太大了所以要用分块的思想。

时间复杂度: O(log⁡n)O(\log n)。

AC Code

C++
#include <bits/stdc++.h>
#define LL long long
using namespace std;

const LL mod = 998244353;
LL n, ans = 2, res = 0;

void work(){
	LL num = 1, cnt = 1, tot = 1;
	while(tot + 2 * cnt <= n){
		num++, cnt *= 2, tot += cnt;
		ans += ((num % mod) * (cnt % mod)) % mod;
	}
	ans += (((n - tot) % mod) * ((num + 1) % mod)) % mod;
	ans %= mod;
}

int main(){
	cin >> n;
	n -= 1;
	work();
	cout << ((ans % mod) + (n % mod)) % mod << "\n";
	return 0;
}

最后总结一下这种题的思路:

如果 nn 很大那么这题一定是找规律,先把 f(i)f(i) 打表打出来再找规律。

记得点赞哦!

The End.

当我改完题解时这道题已经不在接受新题解了。。。

原文