提供一种好想好写的 做法。
观察所求式子,可以分为三个要素分析:,,。 启发我们利用加法结合律、交换律,二进制取 启发我们按位考虑, 和 的组合进一步肯定了拆位。
于是考虑拆位,我们枚举每一位 ,我们要求 的三元组 的对数,我们不妨令 ,我们考虑 和 ,若这两个数相同,无论 还是 取到最小值,我们只需要保证 的第 位为 即可,这是容易计数的,确定 后,你可以知道 的第 位是什么,记作 ,那么枚举 的第一位是哪里,计数即可。
接下来考虑 ,若我们确定了 ,那么我们就可以知道 的值。注意到 与 不同的第一位恰好是 与 不同的第一位,这启发我们枚举这一位的值,但是由于你还要保证前缀相同,所以你需要枚举这个前缀,然后计算在这个前缀中,有多少个 为需要的定值,并确定大小关系,就可以求出 在 和 上的值,最后枚举 的第一位,计数即可。实现上用 trie 维护即可。
胡乱实现也能做到 ,精细实现可以做到 。
code
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using db = double;
using ldb = long double;
using lll = __int128;
using ulll = unsigned __int128;
#define int ll
const int N = 2e5 + 5, P = 29, M = N * (P + 1), mod = 998244353;
int n, m, a[N], V, cnt[N][P + 1][2], pw[P + 1], ans;
int get(int r, int l) {
if (r < l) return 0;
return ((1 << (r - l + 1)) - 1) << l;
}
int calc(int i, int x, int j, int y) {
int res = (m & get(P, i + 1)) >> 2;
if (((m >> i) & 1) != x) {
if (((m >> i) & 1) > x)
res += 1 << (i - 1);
return res;
}
res += (m & get(i - 1, j + 1)) >> 1;
if (((m >> j) & 1) != y) {
if (((m >> j) & 1) > y)
res += 1 << j;
return res;
}
res += m & get(j - 1, 0);
return res;
}
struct trie {
int tot, son[M][2], l[M], r[M];
#define ls son[p][0]
#define rs son[p][1]
void init() {
tot = 1;
memset(l, 63, sizeof l);
}
void insert(int x) {
int p = 1;
for (int i = P; i >= 0; --i) {
int w = (x >> i) & 1;
if (!son[p][w]) son[p][w] = ++tot;
p = son[p][w];
}
}
void dfs(int p, int x, int i) {
if (i < 0) {
l[p] = r[p] = lower_bound(a + 1, a + V + 1, x) - a;
--l[p];
return;
}
if (ls) dfs(ls, x, i - 1);
if (rs) dfs(rs, x | (1 << i), i - 1);
l[p] = min(l[ls], l[rs]);
r[p] = max(r[ls], r[rs]);
}
void solve(int p, int i) {
if (!p) return;
if (ls && rs) {
for (int j = i - 1; j >= 0; --j) {
int c[2][2] = { { cnt[r[ls]][j][0] - cnt[l[ls]][j][0],
cnt[r[ls]][j][1] - cnt[l[ls]][j][1]},
{ cnt[r[rs]][j][0] - cnt[l[rs]][j][0],
cnt[r[rs]][j][1] - cnt[l[rs]][j][1]} };
for (int x = 0; x <= 1; ++x)
for (int y = 0; y <= 1; ++y)
(ans += 2 * c[0][y] * c[1][y ^ 1] % mod * calc(i, x, j, x ^ y ^ 1) % mod * pw[j]) %= mod;
}
}
solve(ls, i - 1), solve(rs, i - 1);
}
} tr;
signed main() {
ios::sync_with_stdio(0), cin.tie(0);
tr.init();
pw[0] = 1;
for (int i = 1; i <= P; ++i) pw[i] = (pw[i - 1] * 2) % mod;
cin >> n >> m;
++m;
map<int, int> mp;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
++mp[a[i]];
tr.insert(a[i]);
}
sort(a + 1, a + n + 1);
V = unique(a + 1, a + n + 1) - a - 1;
for (int i = 1; i <= V; ++i) {
int ct = mp[a[i]];
for (int j = 0; j <= P; ++j) {
cnt[i][j][0] = cnt[i - 1][j][0];
cnt[i][j][1] = cnt[i - 1][j][1];
cnt[i][j][(a[i] >> j) & 1] += ct;
}
}
for (int j = 0; j <= P; ++j)
for (int x = 0; x <= 1; ++x)
(ans += cnt[V][j][x] * cnt[V][j][x] % mod * calc(P + 1, 0, j, x ^ 1) % mod * pw[j]) %= mod;
tr.dfs(1, 0, P);
tr.solve(1, P);
cout << ans;
return 0;
}