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

题目链接

题目

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

(A[l1]A[l1+1]A[r1])+(A[l2]A[l2+1]A[r2]),其中 1l1r1<l2r2Nxy 表示 xy 的按位异或。

思路

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

至于 lmxrmx 怎么求,以 lmx 为例,lmxi=max(lmxi1,find(ai))

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

ai 表示异或前缀和。

总结

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 @   zhangtingxi  阅读(154)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示