P7003 [NEERC2013]Hack Protection

P7003 [NEERC2013]Hack Protection

题意

给定一个序列 a ,求有多少个区间满足区间内的数的异或和等于与的和的值。

思路

首先我们求一个异或前缀和 s,对于每一个区间 [l,r] ,它的贡献为区间内按位与的和等于 srsl1 的段的个数。

x 为某个区间的按位与的和,上面的也就是:

srsl1=x  sr=xsl1

发现,如果我们固定 xsl1 ,那么 sr 就是固定的,我们就可以求区间内与 sr 相等的数的个数来统计答案。

考虑枚举 l ,发现,对于往后按位与的过程,x (与上文定义相同)最多会变化 log 次,我们就可以将其分为这么多段,然后在 s 中求与 sr 相等的数的个数就可以了。

求每一段的按位与结果,可以记录变成 0 的那一位是什么,或者直接 st 表查询都行。

对于最后一个问题,我们可以用主席树,或者简单地离散化加 vector 上二分即可。

实现

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cctype>
#include<cstring>
#include<cmath>
#include<vector>
#include<utility>
#define int unsigned 
using namespace std;
inline int read(){
	int w=0,x=0;char c=getchar();
	while(!isdigit(c))w|=c=='-',c=getchar();
	while(isdigit(c))x=x*10+(c^48),c=getchar();
	return w?-x:x;
}
namespace star
{
	const int maxn=1e5+10;
	int pre[maxn][35],n,a[maxn],b[maxn],s[maxn];
	long long ans;
	vector<int> V[maxn];
	pair<int,int> q[35];
	inline void work(){
		n=read();
		for(int i=1;i<=n;i++) s[i]=read(),a[i]=b[i]=a[i-1]^s[i];
		sort(b+1,b+1+n);
		int cnt=unique(b+1,b+1+n)-b-1;
		for(int i=1;i<=n;i++) a[i]=lower_bound(b+1,b+1+cnt,a[i])-b;
		for(int i=1;i<=n;i++) V[a[i]].push_back(i);
		for(int j=0;j<31;j++) pre[n+1][j]=n+1;
		for(int i=n;i;i--)
			for(int j=0;j<31;j++)
				pre[i][j]=((s[i]>>j)&1)?pre[i+1][j]:i;
		for(int l=1;l<=n;l++){
			int tot=0,x=s[l];
			q[0].first=l;
			for(int j=0;j<31;j++)
			if((s[l]>>j)&1) q[++tot]=make_pair(pre[l][j],j);
			q[++tot]=make_pair(n+1,0);
			sort(q+1,q+1+tot);
			for(int i=1;i<=tot;i++){
				int y=lower_bound(b+1,b+1+cnt,x^b[a[l-1]])-b;
				if(y<=n and b[y]==(x^b[a[l-1]]))
				ans+=(lower_bound(V[y].begin(),V[y].end(),q[i].first)-lower_bound(V[y].begin(),V[y].end(),q[i-1].first));
				x^=(1<<q[i].second);
			}
		}
		printf("%lld\n",ans);
	}
}
signed main(){
	star::work();
	return 0;
}
posted @   Star_Cried  阅读(89)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示