跳到正文

题解

函数(func)题解

mahaorui2012约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年8月10日
收录
2026年10月19日
更新
2026年11月9日
篇幅
约 4 分钟
获赞
4
题目
P17723

版本

  1. v1当前

记值域为 V≤109V\leq 10^9。记 S(l,r)={al,al+1,...,ar}S(l,r)=\{a_l,a_{l+1},...,a_r\}。

先快速计算 OR(S)∨MEX(S)\text{OR}(S)\lor\text{MEX}(S)。对每个二进制位 2k2^k 分别考虑。若 OR(S)\text{OR}(S) 的 2k2^k 位为 11,即 SS 里至少有一个数的 2k2^k 位为 11,则结果的这一位为 11。否则,需要有 MEX(S)\text{MEX}(S) 的 2k2^k 位为 11,又因为 SS 里面所有数的 2k2^k 位为 00,唯一的使 MEX(S)\text{MEX}(S) 的 2k2^k 位为 11 的情况,即 MEX(S)=2k\text{MEX}(S)=2^k。

对 MEX(S)=2k\text{MEX}(S)=2^k 更为严谨的证明

反证。若 MEX(S)≠2k\text{MEX}(S)\neq 2^k,则又因为 MEX(S)\text{MEX}(S) 的 2k2^k 位为 11,有 MEX(S)>2k\text{MEX}(S)>2^k,所以 2k∈S2^k\in S,所以 OR(S)\text{OR}(S) 的 2k2^k 位为 11,矛盾。

因此,对固定的左端点,满足上述条件的右端点,是一个后缀,且最小的满足条件的右端点单调不减。

更严谨的证明

对固定的左端点 ll,使 OR(S(l,r))\text{OR}(S(l,r)) 的 2k2^k 位为 11 的 r≥lr\geq l 显然是一个后缀。MEX(S(l,r))\text{MEX}(S(l,r)) 单调不减,所以 MEX(S)=2k\text{MEX}(S)=2^k 处是一个区间,这个区间之后的部分(MEX(S(l,r))>2k\text{MEX}(S(l,r))>2^k)都有 OR(S(l,r))\text{OR}(S(l,r)) 的 2k2^k 位为 11(上面证过了)。

综上,对固定的左端点,满足 OR(S(l,r))∨MEX(S(l,r))\text{OR}(S(l,r))\lor\text{MEX}(S(l,r)) 的 2k2^k 位为 11 的右端点,是一个后缀。MEX(S(l,r))=2k\text{MEX}(S(l,r))=2^k 的第一个 rr(若没有则不妨视为 n+1n+1)、OR(S(l,r))\text{OR}(S(l,r)) 的 2k2^k 为 11 的第一个 rr 显然都单调不减,所以最小的,使得 OR(S)∨MEX(S)\text{OR}(S)\lor\text{MEX}(S) 的 2k2^k 位为 11 的 rr 单调不减。

考虑双指针。对每个左端点 ll,找到第一个使得 MEX(S(l,r))=2k\text{MEX}(S(l,r))=2^k,或者存在 l≤j≤rl\leq j\leq r 使得 aja_j 的 2k2^k 位为 11 的 r≥lr\geq l 即可。复杂度 O(nlog⁡V)O(n\log V)。

std
C++
#include <iostream>
#include <cstring>
#define ull unsigned long long
using namespace std;

const int N=2000005,LOGV=30;

int arr[N];
int buc[N];

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	
	int n;
	cin>>n;
	for(int i=1;i<=n;++i){
		cin>>arr[i]; 
	}
    ull ans=0;
	arr[n+1]=(1<<30)-1;
	for(int k=0;k<LOGV;++k){
		int p2k=(1<<k);
		int r=0,cnot=p2k,ccnt=0;
		memset(buc,0,sizeof(buc));
		for(int i=1;i<=n;++i){
			if(i>1){
				ccnt-=bool(arr[i-1]&p2k);
				if(arr[i-1]<min(n,p2k)){
					--buc[arr[i-1]];
					if(!buc[arr[i-1]]){
						++cnot;
					}
				}
			}
			while(r<=n && (r<i || (cnot && !ccnt))){
				++r;
				ccnt+=bool(arr[r]&p2k);
				if(arr[r]<min(n,p2k)){
					if(!buc[arr[r]]){
						--cnot;
					}++buc[arr[r]];
				}
			}ans+=(n-r+1)*(1ull<<k);
		}
	}cout<<ans;
	return 0;
}
原文
存档评论19 条抓取于