Description
给定一个长度为n的序列a[1],a[2],…,a[n],请将它划分为m段连续的区间,设第i段的费用c[i]为该段内所有数字的异或和,则总费用为c[1] or c[2] or … or c[m]。请求出总费用的最小值。
题解:
根据 (a xor b) or b=a or b ( a x o r b ) o r b = a o r b ,最后答案的式子可以化为 sum1 or sum2 or ...sumn s u m 1 o r s u m 2 o r . . . s u m n , sum s u m 表示异或前缀和,也就是选出 m−1 m − 1 个数,与或 sumn s u m n 起来最小,那么我们就可以一位一位的贪心,具体的方法是从高到低位,看 sumn s u m n 为 0 0 的每一位是否有个0,若有,那么这一位可以为 0 0 ,把这一位为的数都标记为不能选即可,否则这位一定为 1 1 <script type="math/tex" id="MathJax-Element-529">1</script>。
代码:
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define pa pair<int,int>
const int Maxn=500010;
const LL inf=(1LL<<62);
LL read()
{
LL x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+(ch^48),ch=getchar();
return x*f;
}
int n,m;
LL a[Maxn],sum[Maxn];
bool mark[Maxn];
int main()
{
n=read(),m=read();
sum[0]=0;
for(int i=1;i<=n;i++)a[i]=read(),sum[i]=sum[i-1]^a[i];
LL ans=sum[n];
int c=0;
for(int i=60;i>=0;i--)
if(!(ans&(1LL<<i)))
{
int cnt=0;
for(int j=1;j<n;j++)
if(!mark[j]&&!(sum[j]&(1LL<<i)))cnt++;
if(cnt<m-1)ans|=(1LL<<i);
else
{
for(int j=1;j<n;j++)
if(!mark[j]&&sum[j]&(1LL<<i))mark[j]=true;
}
}
printf("%lld",ans);
}