跳到正文

题解

题解:P8019 [ONTAK2015] OR-XOR

lonys约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年11月15日
收录
2026年11月15日
更新
2026年11月15日
篇幅
约 3 分钟
题目
P8019

版本

  1. v1当前

[ONTAK2015] OR-XOR 题解

前言

这题我写了两篇题解。

分析

考虑将费用表示出来。

令 pip_i 表示第 ii 段的终止位置,sis_i 表示前缀异或和。

特别地,p0=0p_0 = 0,pn=np_n = n。

那么,费用可以表示成:

(sp1⊕sp0)or⁡(sp2⊕sp1)or⁡…or⁡(spn⊕spn−1)(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}})

即:

sp1or⁡(sp2⊕sp1)or⁡…or⁡(spn⊕spn−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}})

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

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

左值右值结果
000000
001111
110011
111111

此时,我们惊讶地发现:

aor⁡(a⊕b)=aor⁡ba \operatorname{or} (a \oplus b) = a \operatorname{or} b

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

sp1or⁡sp2or⁡…or⁡spns_{p_1} \operatorname{or} s_{p_2} \operatorname{or} \ldots \operatorname{or} s_{p_n}

其中,pnp_n 恒定为 nn。

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

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

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

代码实现

如果你 WA 5050 pts

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

参考代码
C++
#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;
}
原文