P3917 异或序列

题目链接

按位考虑,计算有多少个区间异或值使得该位为1,因为该位为1才有贡献。

对每一位异或前缀,记录1,0的个数,易知最终结果是01的个数相乘。

cpp 复制代码
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
	
	int n;
	cin >> n;

	vector<int> a(n);
	for (int i = 0; i < n; i++) {
		cin >> a[i];
	}    

	ll ans = 0;
	for (int i = 0; i < 30; i++) {
		int cnt[2]{1, 0};   //单独的1也有贡献,所以0的个数初始化为1
		int x = 0;

		for (int j = 0; j < n; j++) {
			x ^= a[j] >> i & 1;
			cnt[x]++;
		}
		ans += 1LL * cnt[0] * cnt[1] * (1 << i);
	}

	cout << ans << "\n";

    return 0;
}
相关推荐
anew___16 小时前
蜂鸣器播放音乐——让 Arduino 唱出旋律
c++·stm32·单片机·嵌入式硬件·c
stolentime17 小时前
洛谷P10515 转圈题解
c++·算法·数学建模·贪心算法
tdtsmt18 小时前
穿戴硬件量产工艺实录:天地通电子智能手表主板 SMT 贴片案
c++
m0_7345717621 小时前
深入理解C++ 析构函数<一>基本概念
开发语言·c++
t-think1 天前
C++ string 类(上)—— string类初识与常用接口详解
开发语言·c++
cpp_learners1 天前
C++ 实现责任链模式(Chain of Responsibility):从一堆 if-else 到可插拔的处理管道
开发语言·c++·责任链模式
郝学胜_神的一滴1 天前
C++11 工程级应用 12:编译期类型魔法,干掉重复与臃肿的代码
c++·visual studio
David猪大卫1 天前
【C++修炼】哈希表的实现
数据结构·c++·笔记·学习·算法·哈希算法·散列表
广州山泉婚姻1 天前
列表初始化:C++11全新初始化体系
c++·人工智能
莫生灬灬1 天前
灵码 LingBuilder:用中文写代码,确定性生成真实 C++ 工程(开源)
c++·开源·mfc