// 查询异或最大值,每次插入和查询时间都是log(C)
template<class T>
class trie01 {
vector<vector<T>> tree;
public:
trie01() : tree(1, vector<T>(2, 0)) {}
// 插入待检查的数字
void insert (T x)
{
int p = 0;
for(int i = sizeof(x)*8-2; i >= 0; --i)
{
bool o = (x&((T)1<<i));
if(tree[p][o] == 0)
{
tree[p][o] = tree.size();
tree.emplace_back(2,0);
}
p = tree[p][o];
}
}
// 查询在插入的数字中,返回与x异或后的最大值
T match (T x)
{
T t = x, p = 0;
// 从高位到低位
for(int i = sizeof(x)*8-2; i >= 0; --i)
{
bool o = (x&((T)1<<i));
if(tree[p][!o])
p = tree[p][!o], t = t|((T)1<<i);
else if(tree[p][o])
p = tree[p][o], t = t&(~((T)1<<i));
}
return t;
}
};
已通过 [数组中两个数的最大异或值](421. 数组中两个数的最大异或值 - 力扣(Leetcode))
template<class T>
class trie01 {
vector<vector<T>> tree;
public:
trie01() : tree(1, vector<T>(2, 0)) {}
void insert (T x)
{
int p = 0;
for(int i = sizeof(x)*8-2; i >= 0; --i)
{
bool o = (x&((T)1<<i));
if(tree[p][o] == 0)
{
tree[p][o] = tree.size();
tree.emplace_back(2,0);
}
p = tree[p][o];
}
}
T match (T x)
{
T t = x, p = 0;
// 从高位到低位
for(int i = sizeof(x)*8-2; i >= 0; --i)
{
bool o = (x&((T)1<<i));
if(tree[p][!o])
p = tree[p][!o], t = t|((T)1<<i);
else if(tree[p][o])
p = tree[p][o], t = t&(~((T)1<<i));
}
return t;
}
};
class Solution {
public:
int findMaximumXOR(vector<int>& nums) {
trie01<int> trie;
trie.insert(nums[0]);
int res = 0;
for(auto &a : nums)
res = max(res, trie.match(a)), trie.insert(a);
return res;
}
};
已通过 [E. Sausage Maximization](Problem - 282E - Codeforces)
#include <iostream>
#include <vector>
using namespace std;
using ll = long long;
template<class T>
class trie01 {
vector<vector<T>> tree;
public:
trie01() : tree(1, vector<T>(2, 0)) {}
void insert (T x)
{
int p = 0;
for(int i = sizeof(x)*8-2; i >= 0; --i)
{
bool o = (x&((T)1<<i));
if(tree[p][o] == 0)
{
tree[p][o] = tree.size();
tree.emplace_back(2,0);
}
p = tree[p][o];
}
}
T match (T x)
{
T t = x, p = 0;
// 从高位到低位
for(int i = sizeof(x)*8-2; i >= 0; --i)
{
bool o = (x&((T)1<<i));
if(tree[p][!o])
p = tree[p][!o], t = t|((T)1<<i);
else if(tree[p][o])
p = tree[p][o], t = t&(~((T)1<<i));
}
return t;
}
};
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
trie01<ll> trie;
int n; cin>>n;
vector<ll> arr(n);
ll sum = 0, res = 0;
for(auto &a : arr) {
cin >> a;
sum ^= a;
res = max(res, a);
trie.insert(sum);
}
sum = 0;
for(int i = n-1; i >= 0; --i)
{
sum ^= arr[i];
res = max(res, trie.match(sum));
}
cout << res << endl;
return 0;
}
标签:01trie,int,res,trie01,trie,异或,vector,--,模板
From: https://www.cnblogs.com/hellozhangjz/p/17537399.html