[codevs3311]起床困难综合症

本文介绍了一种使用二进制枚举进行优化选择的算法,并通过具体实例讲解了如何实现这一算法。该算法主要应用于求解最优值问题,在不超过特定约束条件下找到最佳方案。

题目←

wwq:这题你居然没一眼切?!
嗯……二进制枚举……
判断不超过m的二进制数的每一位是1更优还是0更优
显然同时满足我们要放0
为了便于判断大小,从高位到低位枚举
复杂度 2*n*log(m)

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#define LL long long
using namespace std;
const LL MAXN = 100000 + 50;
LL n,m;
struct zt
{
    LL ch,num;
}ope[MAXN];
string x;
LL len;
LL ans;
LL check(LL loc,LL v)
{
    if(v)v <<= loc;
    for(LL i = 1;i <= n;i ++)
    {
        if(ope[i].ch == 1)
        {
            if((ope[i].num & v) == 0)
                v = 0;
        }
        else if(ope[i].ch == 2)
        {
            if(ope[i].num & (1 << loc))
                v = (1 << loc);
        }
        else if(ope[i].ch == 3)
        {
            if(ope[i].num & (1 << loc))
                if(v)v = 0;
                else v = (1 << loc);
        }
    }
    return v;
}
LL now,maxn;
int main()
{
    scanf("%lld%lld",&n,&m);
    for(LL i = 1;i <= n;i ++)
    {
        cin >> x;
        if(x == "AND"){
            ope[i].ch = 1;
        }
        else if(x == "OR"){
            ope[i].ch = 2;
        }
        else if(x == "XOR"){
            ope[i].ch = 3;
        }
        scanf("%d",&ope[i].num);
        maxn = max(maxn,ope[i].num);
    }
    len = log2(maxn);
    for(LL i = len;i >= 0;i --)
    {
        LL tmp1 = check(i,1);
        LL tmp2 = check(i,0);
        if(now + (1 << i) > m || tmp2 >= tmp1)
        {
            ans += tmp2;
        }
        else if(tmp1 > tmp2)
        {
            ans += tmp1;
            now += (1 << i);
        }
    }
    printf("%lld",ans);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值