整数数组中最大异或次级的解决方案

Solution for maximum xor secondary in an array of integers

本文关键字:解决方案 数组 整数      更新时间:2023-10-16

我正在尝试解决这个代码力问题

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::mapupper_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].secondA查找索引it_after找到(现在感觉P跟踪每个子序列中的最后一个元素(?)),并且如果current_valueA中使用该值的 XOR 比任何早期结果候选者都多 (res), 然后使用新的较大值更新res

它对P_rev做类似的事情。

最后。。。

P.insert(S[i].second);
P_rev.insert(S[i].second);

Acurrent_value的索引添加到P,并为将来的迭代P_rev

因此,虽然我还没有解释算法为什么或如何工作(我什至没有阅读问题陈述),但我认为这应该清楚地表明C++在做什么,这就是你所说的你正在努力解决的问题 - 其余的你靠自己;-)。

相关文章: