官方题解|添加元素让数组变为好数组
2024-03-22 11:39:36
发布于:浙江
10阅读
0回复
0点赞
提示
题目解析
任意数字与自己异或的结果为 。
令原数组和为 ,异或和为 ,那么显然我们可以在数组后添加两个元素: 和 。
这样对于添加元素后的数组的和为 ,异或和为 ,满足题目要求。
AC代码
#include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int _; cin >> _;
while (_--) {
int n; cin >> n;
auto sum = 0LL, xsum = 0LL;
for (int i = 0; i < n; ++i) {
int x; cin >> x;
sum += x;
xsum ^= x;
}
cout << 2 << '\n';
cout << xsum << ' ' << sum + xsum << '\n';
}
return 0;
}
复杂度分析
遍历一遍数组求得 和 ,时间复杂度 。
这里空空如也
有帮助,赞一个