ABC452E You WILL Like Sigma Problem

· · 题解

首先提取公因式:把 a_i 提出来,然后就变成了对每个 i 求 \sum_{j = 1}^m (i\bmod j)\times b_j 了。

然后考虑这个 i\bmod j。假如我们钦定了 j,那么随着 i 的增大,这个系数是呈现周期性变化的。即 0,1,\cdots, j-1 然后重复。然后这个东西是一个等差数列。

对于每个 i 用数组维护他所需乘的值,然后枚举 j 然后不断地进行区间加等差数列,然后下一个区间的 l' 就是这次区间的 r + 1。

这个复杂度是 O(\sum_{i = 1}^m \frac{n}{i})。调和级数的总复杂度大约是 O(n \log n),这里至多为调和级数。

Code

#include <bits/stdc++.h>

using namespace std;

#define int long long
using i64 = long long;

const int N = 1e6 + 10, P = 998244353;

int n, m, a[N], b[N];
i64 s[N];

signed main()
{
    cin.tie(0)->ios::sync_with_stdio(false);
    cin >> n >> m;
    for (int i = 1; i <= n; i++) cin >> a[i];
    for (int i = 1; i <= m; i++) cin >> b[i];
    for (int i = 2; i <= m; i++) {
        for (int j = i, l = 1; j - i <= n; j += i) {
            s[l] = (s[l] + b[i]);
            s[j] = (s[j] - (j - l + 1) * b[i] % P + P) % P;
            s[j + 1] = (s[j + 1] + (j - l) * b[i] % P) % P;
            l = j + 1;
        }
    }
    for (int i = 1; i <= n; i++) {
        s[i] += s[i - 1];
        if (s[i] >= P) s[i] -= P;
    }
    for (int i = 1; i <= n; i++) {
        s[i] += s[i - 1];
        if (s[i] >= P) s[i] -= P;
    }
    i64 ans = 0;
    for (int i = 1; i <= n; i++) ans = (ans + a[i] * s[i] % P) % P;
    cout << ans;
    return 0;
}