题解:P8019 [ONTAK2015] OR-XOR

· · 题解

[ONTAK2015] OR-XOR 题解

前言

这题我写了两篇题解。

分析

考虑将费用表示出来。

令 p_i 表示第 i 段的终止位置,s_i 表示前缀异或和。

特别地,p_0 = 0,p_n = n。

那么,费用可以表示成:

(s_{p_1} \oplus s_{p_0}) \operatorname{or} (s_{p_2} \oplus s_{p_1}) \operatorname{or} \ldots \operatorname{or} (s_{p_n} \oplus s_{p_{n-1}})

即:

s_{p_1} \operatorname{or} (s_{p_2} \oplus s_{p_1}) \operatorname{or} \ldots \operatorname{or} (s_{p_n} \oplus s_{p_{n-1}})

那么这个式子(a \operatorname{or} (a \oplus b))能不能化简呢?

相信很多人都能看出来,但对于这种位运算的化简,有一种固定的方法:真值表。

左值 右值 结果
0 0 0
0 1 1
1 0 1
1 1 1

此时,我们惊讶地发现:

a \operatorname{or} (a \oplus b) = a \operatorname{or} b

所以,刚才的式子,由结合律,变成:

s_{p_1} \operatorname{or} s_{p_2} \operatorname{or} \ldots \operatorname{or} s_{p_n}

其中,p_n 恒定为 n。

所以,思路几乎明确了:从高位到低位贪心,让答案尽可能小。

至于为什么,就是因为下面这个式子:

\sum_{i=0}^{n} 2^i = 2^{n+1} - 1

代码实现

::::warning[如果你 WA 50 pts]

你最后要或上一个 s_n,那么,你是不是要直接放弃一些位?

::::

::::success[参考代码]{open}

#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m;
vector<int>a;
inline void run(int x){
    int cnt=0;
    vector<int> d;
    for(auto i:a){
        if(!(i&(1ll<<(x-1)))){
            cnt++;
            d.push_back(i);
        }
    }
    if(cnt>=m-1)a=d;
}
signed main(){
    cin.tie(0)->sync_with_stdio(false);
    cin>>n>>m;
    int cur=0;
    for(int i=0;i<n;i++){
        int x;
        cin>>x;
        if(i!=0)x^=a[i-1];
        if(i!=n-1)a.push_back(x);
        else cur=x;
    }
    for(int i=61;i>=1;i--){
        if(!(cur&(1ll<<(i-1))))run(i);
    }
    int ans=cur;
    for(auto i:a){
        ans|=i;
    }
    cout<<ans;
    return 0;
}

::::