题解:AT_abc384_f [ABC384F] Double Sum 2

· · 题解

[ABC384F] Double Sum 2 题解

solution

题目里的 f 函数正着做显然性质很不好,O(n ^ 2) 的暴力几乎没有优化余地。正难则反,\displaystyle \sum _ {i = 1} ^ {N} \displaystyle \sum _ {j = i} ^ {N} (A _ i + A _ j) 显然是好求的,设它为 ans,考虑减掉多的部分。

可以发现,如果设 x 最低位的 1 所在的位为 y, 那么有 f(x) = \frac {1} {2 ^ y} x,也就是需要减掉 \frac {2 ^ y - 1} {2 ^ y} x,但是这样还是没法做,因为最低位的 1 这个东西的性质还是不太好。看到 x 前的系数,我们可以敏锐地想到这个东西等于 \displaystyle \sum _ {k = 1} ^ {y} \frac {1} {2 ^ k} ,此时对 k 的约束相当于 x 是 2 ^ k 的倍数。

换个角度想,也就是说对于每个 2 ^ k,设所有和为其倍数的 (i, j) 对权值之和为 sum,答案就要减去 \frac {sum} {2 ^ k},这就可以通过开 map 记录每一个权值下的个数与权值和来做了。

code

与上文变量名不同,请注意分辨。

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 2e5 + 5;
int n, a[N], ans;
unordered_map <int, int> cnt, mp;
signed main() {
    cin.tie(0) -> sync_with_stdio(false);
    cin >> n;
    for (int i = 1; i <= n; ++i) cin >> a[i];
    int now = 0;
    for (int i = 1; i <= n; ++i) now += a[i], ans += now + i * a[i];
    for (int i = 2; i < 2e7; i <<= 1) {
        int now = 0;
        for (int j = 1; j <= n; ++j) {
            ++cnt[a[j] % i];
            mp[a[j] % i] += a[j];
            now += mp[(i - a[j] % i) % i] + a[j] * cnt[(i - a[j] % i) % i];
        }
        for (int j = 1; j <= n; ++j) {
            --cnt[a[j] % i];
            mp[a[j] % i] -= a[j];
        }
        ans -= now / i;
    }
    cout << ans;
}