题解:P11397 界分数

· · 题解

这是本蒟蒻写的第一篇题解,也是第一道场切的绿题,当时交不了题解了,现在发现又能交了,希望管理员给个通过。

思路:

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

直接开始打标找 f_{i} 的规律:

i 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
f(i) 1 2 3 3 4 4 4 4 5 5 5 5 5 5 5 5 6 6 6 6

容易发现这个序列中 f_{i} 这个数出现的次数为 2^{i-2}(f_{1} 除外)然后我们可以把题目转换为 1+2+2+3+3+3+3+4+4+4+4+4+4+4+4...... 这个序列前 n-1 的项和在加 n 的和。

优化:

因为 1 \le n \le 10^{18},所以暴力枚举数列前 n 项再求和会超时。但是由于序列中每个数出现的次数有规律,所以可以将数列分成 \log n 块,然后就不会超时了。

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

代码:

#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;
}