题解:P17723 [SCP-S 2026] 函数 / func

· · 题解

推荐来做观察相似的 Another Bitwise Interactive Problem。

尊重题目,题解中用 \lor 表示按位或。

考虑什么时候 \operatorname{OR}(S)\lor\operatorname{MEX}(S)\neq \operatorname{OR}(S)。

注意到这当且仅当 \operatorname{MEX}(S)=2^k,其中 k 为非负整数。为什么?[0,2^k] 所有数的或和为 2^{k+1}-1,而假如 \operatorname{MEX} 在 [2^k+1,2^{k+1}-1] 范围内,那么或和仍然为 2^{k+1}-1。

所以做完了,我们先算出所有区间的或和,这个是经典题目,拆位,遍历右端点 r=1,2\cdots,n,对于每一位 j,维护这一位上一次出现的位置 lst_j,那么左端点就可以取 [1,lst_j]。

根据上面的结论,枚举 k,我们再统计出有多少个区间的 mex 为 2^k,且未出现第 k 位为 1 的数,固定左端点,右端点的 mex 值为单调的,所以双指针维护 r 满足 \operatorname{MEX}=2^k 的区间,如果遇到了第 k 位为 1 的区间那么直接跳到 r 即可,假如对于 i,[i,r] 为 r 最小且满足上面条件的区间,那么左端点 i 的贡献为 nxt_r-r,其中 nxt_r 为 r 下一个第 r 位为 1 的下标。

时间复杂度 O(n\log V)。

#include<bits/stdc++.h>
using namespace std;
#define ull unsigned long long

const int N=2e6+5;
ull ans;
int n,a[N];
int lst[N],cnt[N],nxt[N];

signed main(){
    ios::sync_with_stdio(0);cin.tie(0);
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    for(int i=1;i<=n;i++){
        for(int j=0;j<30;j++) if(a[i]>>j&1) lst[j]=i;
        for(int j=0;j<30;j++) ans+=(1ll<<j)*lst[j];
    }
    for(int j=0;j<21;j++){
        int r=0,c=(1<<j);
        nxt[n+1]=n+1;
        for(int i=n;i>=1;i--){
            if(a[i]>>j&1) nxt[i]=i;
            else nxt[i]=nxt[i+1];
        }
        for(int i=1;i<=n;i++){
            while(1){
                if(!c) break;
                if(r==n) break;
                r++;
                if(a[r]<(1<<j)){
                    if(!cnt[a[r]]) c--;
                    cnt[a[r]]++;
                }
                if(a[r]&(1<<j)){
                    for(int k=i;k<=r;k++) if(a[k]<(1<<j)) cnt[a[k]]=0;
                    c=(1<<j);
                    i=r;
                    break;
                }
            }
            if(!c) ans+=(nxt[r]-r)*(1ll<<j);
            if(a[i]<(1<<j)&&cnt[a[i]]){
                cnt[a[i]]--;
                if(!cnt[a[i]]) c++;
            }
        }
    }
    cout<<ans;
    return 0;
}