题解:比亚多西

· · 题解

Solution

记 f_i=f(i),考虑在 i-1 个数中加入一个数,会造成怎样的贡献。

容易发现,第一次操作后,i-1 分出的较大的区间和 i 分出的较小的区间长度是相同的,那么新加入的数的贡献就是在不同的那个子问题(i-1 分出的较小区间)中加入新数的贡献 +1。每次区间长度减半(下取整),总共会递归 \lfloor\log_2 i\rfloor 次,故有转移方程:

f_i=f_{i-1}+\lfloor\log_2 i\rfloor+1

考虑计算 [1,R] 的答案,减去 [1,L-1] 的答案即可。对增量 \lfloor\log_2 i\rfloor+1 算贡献,答案为:

\sum_{i=1}^{R}(\lfloor\log_2 i\rfloor+1)\times(R-i+1)

这样就容易优化了,我们枚举 \lfloor\log_2 i\rfloor+1 的值,算出其贡献即可。具体地,\lfloor\log_2 i\rfloor+1=x 的区间为 l=2^{x-1},r=\min(2^{x}-1,n),贡献即为 (2n-l-r+2)(r-l+1)/2。

时间复杂度 \mathcal{O}(\sum\log R),可以取得满分。

很多题解说本题的取模有很多细节,实则并非,这里放一下 std。 :::info[std]


#include <bits/stdc++.h>
#define REP(i, l, r) for (int i = (l); i <= (r); ++ i)
#define DEP(i, r, l) for (int i = (r); i >= (l); -- i)
#define fi first
#define se second
#define pb emplace_back
#define mems(x, v) memset((x), (v), sizeof(x))
using namespace std;
namespace Milkcat {
    typedef long long LL;
    typedef pair<LL, LL> pii;
    const int N = 1e6 + 5, mod = 998244353;
    LL solve(LL n) {
        LL rs = 0;
        REP(i, 1, __lg(n) + 1) {
            LL l = (1LL << (i - 1)), r = min(l * 2 - 1, n);
            LL p = (n - r + 1 + n - l + 1), q = (r - l + 1);
            if (p & 1) p %= mod, q = q / 2 % mod;
            else p = p / 2 % mod, q %= mod;
            rs = (rs + p * q % mod * i + mod) % mod;
        }
        return rs;
    }
    LL L, R, k;
    int main() {
        cin >> L >> R;
        cout << (solve(R) - solve(L - 1) + mod) % mod << '\n';
        return 0;
    }
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    int T = 1; cin >> T;
    while (T --) Milkcat::main();
    return 0;
}
::info