4245: [ONTAK2015]OR-XOR 思路 贪心

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 表示异或前缀和,也就是选出 m1 m − 1 个数,与或 sumn s u m n 起来最小,那么我们就可以一位一位的贪心,具体的方法是从高到低位,看 sumn s u m n 0 0 的每一位是否有m1个0,若有,那么这一位可以为 0 0 ,把这一位为1的数都标记为不能选即可,否则这位一定为 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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值