【Loj #10051. 「一本通 2.3 例 3」Nikitosh 和异或】题解

题目链接

题目

给定一个含 \(N\) 个元素的数组 \(A\),下标从 \(1\) 开始。请找出下面式子的最大值:

\((A[l_1]⨁A[l_1+1]⨁…⨁A[r_1])+(A[l_2]⨁A[l_2+1]…⨁A[r_2])\),其中 \(1≤l_1≤r_1<l_2≤r_2≤N\)\(x⨁y\) 表示 \(x\)\(y\) 的按位异或。

思路

枚举分割点 \(i\),则此时最大值为左边的最大值 \(lmx\) 和右边的最大值 \(rmx\) 的和。

至于 \(lmx\)\(rmx\) 怎么求,以 \(lmx\) 为例,\(lmx_i=\max(lmx_{i-1}, find(a_i))\)

\(find(a_i)\) 的过程本质上就是在trie树上找离 \(a_i\) 最远的点。

\(a_i\) 表示异或前缀和。

总结

A玩感觉自己的思路好像错了,应该是把前缀和丢到trie树上,但是却对了。

后来改成前缀和之后,也AC了,说明前缀和是真的可以。

也侧面说明了数据的弱。

把前缀和丢trie树的时候,记得一定要丢0。

另一方面,对于这种分两段的题,我想不到用前缀和,只有分一段才想到。

其实对于分两段,可以前后各做一次前缀和并统计,然后枚举中间点合并,理论时间复杂度与分一段的复杂度是一样的。

Code

// Problem: 1473:【例题3】Codechef REBXOR
// Contest: SSOIER
// URL: http://ybt.ssoier.cn:8088/problem_show.php?pid=1473
// Memory Limit: 131 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;
//#define int long long
inline int read(){int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;
ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+
(x<<3)+(ch^48);ch=getchar();}return x*f;}
//#define M
//#define mo
#define N 400010
struct node
{
	int s[2]; 
}d[N*30]; 
int n, m, i, j, k; 
int a[N], b[N], lmx[N], rmx[N]; 
int cnt, ans; 

void trie(int x)
{
	int i, j, p=1; 
	for(i=30; i>=0; --i)
	{
		j= (x& (1<<i)) > 0; 
		if(!d[p].s[j]) d[p].s[j]=++cnt; 
		p=d[p].s[j]; 
	}
}

int dfs(int dep, int x, int k, int now)
{
	if(dep<0) return now; 
	int i=((x&(1<<dep))>0), j=i^1; 
	if(d[k].s[j]) return dfs(dep-1, x, d[k].s[j], now|(1<<dep)); 
	else return dfs(dep-1, x, d[k].s[i], now); 
}

signed main()
{
//	freopen("tiaoshi.in", "r", stdin); 
//	freopen("tiaoshi.out", "w", stdout); 
	n=read(); 
	for(i=1; i<=n; ++i) b[i]=read(); 
	memset(d, 0, sizeof(d));
	cnt=1; trie(0); 
	for(i=1; i<=n; ++i)
	{
		a[i]=(a[i-1]^b[i]); 
		// printf("%d ", a[i]); 
		trie(a[i]); 
		lmx[i]=max(lmx[i-1], dfs(30, a[i], 1, 0)); 
	}
	// printf("\n"); 
	memset(d, 0, sizeof(d)); 
	cnt=1; trie(0); 
	for(i=n; i>=1; --i)
	{
		a[i]=(a[i+1]^b[i]); 
		// printf("%d ", a[i]); 
		trie(a[i]); 
		rmx[i]=max(rmx[i+1], dfs(30, a[i], 1, 0)); 
	}
	// for(i=1; i<=n; ++i) printf("%d ", lmx[i]); printf("\n"); 
	// for(i=1; i<=n; ++i) printf("%d ", rmx[i]); printf("\n"); 
	for(i=1; i<n; ++i) ans=max(ans, lmx[i]+rmx[i+1]); 
	// printf("\n"); 
	printf("%d", ans); 
	return 0; 
}

posted @ 2022-01-12 09:49  zhangtingxi  阅读(133)  评论(0编辑  收藏  举报