函数(func)题解

· · 题解

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

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

:::success[对 \text{MEX}(S)=2^k 更为严谨的证明] 反证。若 \text{MEX}(S)\neq 2^k,则又因为 \text{MEX}(S) 的 2^k 位为 1,有 \text{MEX}(S)>2^k,所以 2^k\in S,所以 \text{OR}(S) 的 2^k 位为 1,矛盾。 :::

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

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

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

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

:::success[std]

#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;
}

:::