整数数组中最大异或次级的解决方案
Solution for maximum xor secondary in an array of integers
我正在尝试解决这个代码力问题
http://codeforces.com/contest/281/problem/D
给定一个整数数组,找到任何子序列中第一个和第二个最大元素的最大 xor ?
我无法找出解决此问题的最佳方法。我阐述的解决技术很少是使用排序,堆栈,但我无法找出正确的解决方案。
我用谷歌搜索并找到了问题设置者的解决方案代码。但是我无法理解 c++ 中的解决方案,我对它很天真。
下面是 c++ 中问题设置者的代码
using namespace std;
using namespace io;
typedef set<int> Set;
typedef set<int, greater<int> > SetRev;
namespace solution {
const int SIZE = 100000 + 11;
int n;
int A[SIZE];
II S[SIZE];
Set P;
SetRev P_rev;
int result;
}
namespace solution {
class Solver {
public:
void solve() {
normalize();
result = get_maximum_xor();
}
int get_maximum_xor() {
int res = 0;
for (int i = 0; i < n; i++) {
int current_value = S[i].first;
Set::iterator it_after = P.upper_bound(S[i].second);
Set::iterator it_before = P_rev.upper_bound(S[i].second);
if (it_after != P.end()) {
int after_value = A[*it_after];
res = max(res, current_value ^ after_value);
}
if (it_before != P_rev.end()) {
int before_value = A[*it_before];
res = max(res, current_value, before_value);
}
P.insert(S[i].second);
P_rev.insert(S[i].second);
}
return res;
}
void normalise() {
for (int i = 0; i < n; i++) {
S[i] = II(A[i], i);
}
sort(S, S + n, greater<II>());
}
}
有人可以解释一下解决方案,我所理解的方法,而不是完全吗?
好的,所以Solver::solve()
首先调用normalise
:
void normalise() {
for (int i = 0; i < n; i++) {
S[i] = II(A[i], i);
}
sort(S, S + n, greater<II>());
}
这样做是获取一个整数A
数组 - 比如{4, 2, 9}
,并填充一个数组S
其中A
的值被排序并与它们出现在A
中的索引配对 - 对于我们的示例,{{2, 1}, {4, 0}, {9, 2}}
。
然后求解器调用get_maximum_xor()
...
for (int i = 0; i < n; i++) {
int current_value = S[i].first;
Set::iterator it_after = P.upper_bound(S[i].second);
Set::iterator it_before = P_rev.upper_bound(S[i].second);
"for i"循环用于从S
(最初来自A
的值)获取连续的排序值。 虽然您还没有发布完整的程序,所以我们无法确定没有任何内容在P
中预填充任何值,但我会假设这一点。 我们确实知道P
是一个std::map
,upper_bound
搜索以找到大于S[i].second
(current_value
出现在A
中的索引)和上面的值P
的第一个元素,然后是类似于P_rev
,这是一个值按降序排序的std::map
, 可能会用与P
相同的值填充它,但我们同样没有代码。
然后。。。
if (it_after != P.end()) {
int after_value = A[*it_after];
res = max(res, current_value ^ after_value);
}
。是说,如果P
中的任何值被>=
S[i].second
,A
查找索引it_after
找到(现在感觉P
跟踪每个子序列中的最后一个元素(?)),并且如果current_value
A
中使用该值的 XOR 比任何早期结果候选者都多 (res
), 然后使用新的较大值更新res
。
它对P_rev
做类似的事情。
最后。。。
P.insert(S[i].second);
P_rev.insert(S[i].second);
将A
中current_value
的索引添加到P
,并为将来的迭代P_rev
。
因此,虽然我还没有解释算法为什么或如何工作(我什至没有阅读问题陈述),但我认为这应该清楚地表明C++在做什么,这就是你所说的你正在努力解决的问题 - 其余的你靠自己;-)。
- 你能帮我解决删除数组 c++ 中重复值的挑战吗?
- 从排序数组中删除重复项,具有不同代码方式的相同解决方案具有不同的输出
- 使用STL对用户输入数组进行排序的错误有什么解决方案吗?
- 我必须找到给定数组中所有数字的周期,就像有很多解决方案,但数组的大小是 10^5
- 寻找C++中数组和cout交互的解决方案
- 如何解决指针数组中的数据依赖关系
- 对于非常大的输入,缺少和重复 1..n 的数字数组.使用1..n系列特性的解决方案.溢出问题
- 比较/搜索数组中多个整数的最佳解决方案
- 递归解决方案,用于显示线性链表数组
- 整数数组中最大异或次级的解决方案
- 我可以使用模板作为多态处理数组的安全解决方案
- 我该如何判断k-server动态解决方案的最佳路径以数组成本[i] [j] [k] [t]位于何处
- 需要在O(n)复杂性中解决的数组编码挑战
- 需要帮助解决特征数组并行构造中的数据争用
- GoogleMock SaveArg 用于保存数组?编译器抛出错误,我还没有看到一个好的解决方案
- 用可以检查边界 c++ 的东西替换数组的最接近的解决方案
- 将一维矩阵数组转换为主一维矩阵的有趣算法挑战,需要有效的解决方案
- 关于C++中的二维数组,我的解决方案有什么问题
- C++对象实例化数组(我正在尝试找到编译时解决方案)
- 给定一个范围,我必须计算数组中数字的频率.给定的解决方案是否有效