P7003 [NEERC2013]Hack Protection

P7003 [NEERC2013]Hack Protection

题意

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

思路

首先我们求一个异或前缀和 (s),对于每一个区间 ([l,r]) ,它的贡献为区间内按位与的和等于 (s_r igoplus s_{l-1}) 的段的个数。

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

[s_r igoplus s_{l-1}=x Leftrightarrow s_r=x igoplus s_{l-1} ]

发现,如果我们固定 (x)(s_{l-1}) ,那么 (s_r) 就是固定的,我们就可以求区间内与 (s_r) 相等的数的个数来统计答案。

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

求每一段的按位与结果,可以记录变成 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
",ans);
	}
}
signed main(){
	star::work();
	return 0;
}
原文地址:https://www.cnblogs.com/BrotherHood/p/14034797.html