D. Sum of XOR Functions
D. Sum of XOR Functions
You are given an array of length consisting of non-negative integers.
You have to calculate the value of , where is (the character denotes bitwise XOR).
Since the answer can be very large, print it modulo .
Input
The first line contains one integer () — the length of the array .
The second line contains integers (.
Output
Print the one integer — the value of , taken modulo .
Examples
Input
3
1 3 2
Output
12
Input
4
39 68 31 80
Output
1337
Input
7
313539461 779847196 221612534 488613315 633203958 394620685 761188160
Output
257421502
Note
In the first example, the answer is equal to .
解题思路
如果涉及到位运算的话一般都是按位来考虑,并且每一位的计算是相互独立的。对于 ,我们把 看成是二进制转十进制的形式,例如有 。由于 的最大取值是 ,因此在二进制下最多有 位,在按位的考虑的思想下, 的结果可以看成是 的形式,其中 表示考虑每个 的第 位时 的结果,有 , 表示 在二进制下第 位的数值。
当我们考虑按位计算是,本质上是处理由 构成的 串,因此 的值不是 就是 ,而只有当 时才有意义。为此我们应该统计所有 的连续子串的长度总和。我们按右端点来对所有连续子串进行分类,当其右端点 固定后,我们要找到所有满足 的 ,其中 。为了方便这里定义前缀异或和 ,因此就等价于找到所有满足 的 ,然后再累加这些 到 的长度,也就是子串的长度。为此可以开个两个哈希表 和 ,分别维护 中 的下标数量,以及对应的下标的和。因此当 固定后,满足 的子串长度总和就是 ,对总的答案的贡献就是 。
AC 代码如下,时间复杂度为 :
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 3e5 + 10, mod = 998244353;
int a[N];
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", a + i);
}
int ret = 0;
for (int k = 0; k <= 29; k++) {
int sum = 0, c[2] = {0}, s[2] = {0};
for (int i = 1; i <= n; i++) {
c[sum]++, s[sum] = (s[sum] + i - 1) % mod;
int x = a[i] >> k & 1;
sum ^= x;
ret = (ret + (1ll * c[sum ^ 1] * i % mod - s[sum ^ 1] + mod) % mod * (1 << k)) % mod;
}
}
printf("%d\n", ret);
return 0;
}
参考资料
Educational Codeforces Round 155 — Editorial:https://codeforces.com/blog/entry/120773
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/17751732.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
2022-10-09 Using a Robot to Print the Lexicographically Smallest String
2022-10-09 最小移动距离