BZOJ.4245.[ONTAK2015]OR-XOR(贪心)

本文详细解析了一种基于高精度数位的动态规划算法,通过贪心策略解决特定数学问题。算法首先构建前缀和数组,然后从高位到低位判断是否可以将当前位设为0,确保至少有m个位置满足条件。文章提供了完整的C++实现代码,并讨论了复杂度为O(nloga)的解决方案。

题目链接

从高到低位贪心,判断答案的该位能否为0。
求一个前缀和sum。对于最高位,答案的这一位可以为0当且仅当至少存在m个位置满足sum[i]在这一位上为0。
注意sum[n]这一位必须为0。
如果确定高位为0,则高位为1的sum[i]就不能再选(即不能做右端点)。

这样求一遍所有位即可。复杂度\(O(n\log a)\)

//5508kb    768ms
#include <cstdio>
#include <cctype>
#include <algorithm>
//#define gc() getchar()
#define MAXIN 300000
#define gc() (SS==TT&&(TT=(SS=IN)+fread(IN,1,MAXIN,stdin),SS==TT)?EOF:*SS++)
typedef long long LL;
const int N=5e5+5;
const LL LIM=(1ll<<61)-1ll;

int n,m;
bool ban[N];
LL sum[N];
char IN[MAXIN],*SS=IN,*TT=IN;

inline LL read()
{
    LL now=0;register char c=gc();
    for(;!isdigit(c);c=gc());
    for(;isdigit(c);now=now*10+c-'0',c=gc());
    return now;
}
bool OK(int bit)
{
    if(sum[n]>>bit&1) return 0;
    int cnt=0;
    for(int i=1; i<=n; ++i)
        if(!ban[i]&&!(sum[i]>>bit&1))
            if(++cnt==m) break;
    if(cnt<m) return 0;
    for(int i=1; i<=n; ++i)
        if(sum[i]>>bit&1) ban[i]=1;
    return 1;
}

int main()
{
    n=read(),m=read();
    for(int i=1; i<=n; ++i) sum[i]=sum[i-1]^read();
    if(m==1) return printf("%lld\n",sum[n]),0;

    LL ans=0;
    for(int i=60; ~i; --i) if(!OK(i)) ans|=1ll<<i;
    printf("%lld\n",ans);

    return 0;
}

转载于:https://www.cnblogs.com/SovietPower/p/9759961.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值