左神算法学习日记——子数组最大异或和

求子数组最大异或和,要求时间复杂度为O(n)

class Node
{
public:
	Node()
	{
		next[0] = NULL;
		next[1] = NULL;
	}
	//构造之前所有异或和的前缀树
	void addnum(int num)
	{
		Node* trytree = this;
		for (int i = 31; i >= 0; i--)//应该确保高位尽量为1,所有应该从高位开始找,所以前缀树应该从高位开始构造
		{
			int curbit = (num >> i) & 1;
			trytree->next[curbit] = trytree->next[curbit] ? trytree->next[curbit] : new Node();
			trytree = trytree->next[curbit];
		}
	}
	//获取最大异或和
	int getmax(int ero)
	{
		int res = 0;
		Node* trytree = this;
		for (int i = 31; i >= 0; i--)
		{
			int cur = (ero >> i) & 1;
			int best = i == 32 ? cur : (cur ^ 1);
			best= trytree->next[best] ? (best): (best^1);//如果best边不存在则!best边一定存在,因为int是32位的,每一个点必有一条边可以走,而初始化保证了一定存在32条边,33个点
			res |= best^cur<<i;//ero和之前的最优异或和异或并将其赋值给res,注意要将异或结果移到相应的位上
			trytree = trytree->next[best];//遍历下一条边
		}
		return res;
	}
	//计算所有0-i的子数组的最大异或和,并找出其中最大的
	int getallmax(vector<int> arr)
	{
		if (arr.empty())
			return 0;
		int max = arr[0];//当子数组不包括空数组时,max应该用数组的第一个元素进行初始化,以保证不包括空数组的最大异或和为负数时,能得到正确的值。而当子数组包括空数组时应该用0初始化
		int ero = 0;
		addnum(0);//初始化前缀树,才能调用getmax
		for (int i = 0; i < arr.size(); i++)
		{
			ero ^= arr[i];
			max = std::max(max, getmax(ero));
			addnum(ero);
		}
		return max;
	}
  private:
        Node* next[2];
};

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
求1~n数组最大异或和也可以使用类似于求一段区间最大异或和的方法。具体步骤如下: 1. 将1~n数组中的所有数以二进制形式插入到字典树中。 2. 对于每个数,从高位到低位依次匹配字典树上的节点,如果当前位为1,就往字典树的右树走,否则就往左树走。匹配完整个二进制数后,我们可以得到一个最大异或值。 3. 对于1~n数组,我们可以将其中的相邻两个数看作一段区间,然后使用类似于求一段区间最大异或和的方法求出最大异或和。 时间复杂度为O(nlogC),其中n为数组长度,C为数的范围。以下是求1~n数组最大异或和的C++代码: ```c++ #include <iostream> using namespace std; const int MAXN = 100010; const int MAXBITS = 30; struct TrieNode { int cnt; int children[2]; } trie[MAXN * MAXBITS]; int root, node_cnt; void insert(int x) { int p = root; for (int i = MAXBITS - 1; i >= 0; i--) { int idx = (x >> i) & 1; if (!trie[p].children[idx]) { trie[p].children[idx] = ++node_cnt; } p = trie[p].children[idx]; trie[p].cnt++; } } int query(int x) { int p = root, res = 0; for (int i = MAXBITS - 1; i >= 0; i--) { int idx = (x >> i) & 1; if (trie[trie[p].children[idx ^ 1]].cnt > 0) { res += (1 << i); p = trie[p].children[idx ^ 1]; } else { p = trie[p].children[idx]; } } return res; } int main() { int n; cin >> n; root = 1; node_cnt = 1; int pre = 0, ans = 0; for (int i = 1; i <= n; i++) { int x; cin >> x; insert(pre); pre ^= x; ans = max(ans, query(pre)); } cout << ans << endl; return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值