【思维构造】Vampiric Powers, anyone?—CF1847C

Vampiric Powers, anyone?---CF1847C
参考文章

这个思路完美利用了 a i a_i ai 很小的这个特点,通过异或前缀和完美地将循环数组的长度变为循环元素的范围,极快地提升了代码的效率。

思路

手推一遍"召唤"的过程可以发现,能召唤出的最大力量即 a a a 数组中连续子串中元素异或和的最大值。用代码表示就是:

cpp 复制代码
	int res = a[1];
	for (int l = 1; l <= n; l ++) {
		int now = 0;
		for (int r = l; r <= n; r ++) {
			now ^= a[r];
			res = max(res, now);
		}
	}

当然这样是一定会超时的,我们需要考虑一个更高效的方法。

观察题目可以发现, a i < 256 a_i < 256 ai<256 这个条件还没有用到,那么可以发现一个新的思路:

求 a a a 的前缀异或和数组,数组中任意两个元素异或的最大值即为所求。虽然这样也是两层循环,但每层循环的循环次数最多不过 256 256 256 次,可以通过本题。

C o d e Code Code

cpp 复制代码
#include <bits/stdc++.h>
#define int long long
#define sz(a) ((int)a.size())
#define all(a) a.begin(), a.end()
using namespace std;
using PII = pair<int, int>;
using i128 = __int128;
const int N = 1e5 + 10;

int n;
int a[N];

void solve() {
	cin >> n;
	map<int, int> mp;
	mp[0] = 1;
	for (int i = 1; i <= n; i ++) {
		cin >> a[i];
		a[i] ^= a[i - 1];
		mp[a[i]] = 1;
	}
	
	int res = -1;
	for (auto i : mp) {
		if (i.second) {
			for (auto j : mp) {
				if (j.second) {
					res = max(res, i.first ^ j.first);
				}
			}
		}
	}
	
	cout << "         ";
	cout << res << "\n";
}

signed main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	int T = 1;
	cin >> T; cin.get();
	while (T --) solve();
	return 0;
}
相关推荐
随流寻影1 小时前
利用 C++ 实现快速排序及三种优化
开发语言·c++
西西弗Sisyphus1 小时前
C++ 最小 Agentic Loop 实现 - 回调函数系列 - 指针与内存地址(2)
开发语言·c++
西西弗Sisyphus3 小时前
C++ 最小 Agentic Loop 实现 - 回调函数系列 - typedef 封装(4)
c++
笑鸿的学习笔记3 小时前
C++笔记之信号量和引用计数的概念是否等价?
java·c++·笔记
real_metrix5 小时前
【教程】C/C++ 基础系列 - 内存泄漏最佳实践
c++·c·内存泄漏
fqbqrr6 小时前
2612,C++协程
c++
纪念 2297 小时前
C++ 算法模板与错题 (差分)
开发语言·c++·算法
li星野7 小时前
C++/Qt 开发避坑与重构原则清单 (速记版)
c++·qt·重构
西西弗Sisyphus7 小时前
C++ 最小 Agentic Loop 实现 - 回调函数系列 - 函数指针详解(3)
c++
杜 硕7 小时前
从零开始的C++生活——第十六讲
开发语言·数据结构·c++·生活