hdu 5491 The Next 2015合肥网络赛 贪心 位运算

题目

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5491

题目来源:2015合肥网络赛签到题。这套题质量比较高

简要题意: x 二进制含有1的个数为 cnt(x) S1cnt(x)S2 x 是WTH数
    求大于 D 的第一个WTH数。

数据范围:T300000;0D<231;D是WYH数

题解

虽然是签到题,但是这题当时卡了我挺久的,然后最后转手给学长了。

贪心的题目需要制定最好的策略,很容易思路混乱而导致错误。

基本的策略是从低位到高位找为 0 的位,这些位填上了1之后这个数一定是比 D 大的

然后该位之后的所有位就都可以任意设置了。

之后再去判断是否能够设置为目标的数就行了。

实现

要知道一个数有多少位其实是有Θ(loglen)的算法的, len 是数的二进制占位。

这是一个分治的小技巧,可以去看下Matrix67的位运算讲稿学下。

然后g++内部也有用硬件实现的函数__builtin_popcount

做的时候就是扫一遍,对于 1 把它置为0,对于 0 去判断当前置为1用之后的位内否达到目标。

代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <set>
#include <map>

#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
LL powmod(LL a,LL b, LL MOD) {LL res=1;a%=MOD;for(;b;b>>=1){if(b&1)res=res*a%MOD;a=a*a%MOD;}return res;}
// head
inline int bitCount(LL x) {
    x = (x & 0x5555555555555555LL) + ((x >> 1) & 0x5555555555555555LL);
    x = (x & 0x3333333333333333LL) + ((x >> 2) & 0x3333333333333333LL);
    x = (x & 0x0F0F0F0F0F0F0F0FLL) + ((x >> 4) & 0x0F0F0F0F0F0F0F0FLL);
    x = (x & 0x00FF00FF00FF00FFLL) + ((x >> 8) & 0x00FF00FF00FF00FFLL);
    x = (x & 0x0000FFFF0000FFFFLL) + ((x >> 16) & 0x0000FFFF0000FFFFLL);
    x = (x & 0x00000000FFFFFFFFLL) + ((x >> 32) & 0x00000000FFFFFFFFLL);
    return x;
}

LL solve(LL d, int l, int r) {
    for (int i = 0; i < 64; i++) {
        int cnt = bitCount(d);
        if ((d & (1LL<<i)) == 0 && cnt+1 <= r && cnt+i+1 >= l) {
            return d | (1LL<<i) | ((1LL<<max(l-cnt-1, 0))-1);
        }
        d &= -1LL^(1LL<<i);
    }
}
int main()
{
    int t, l, r, cas = 1;
    LL d;
    scanf("%d", &t);
    while (t--) {
        scanf("%I64d%d%d", &d, &l, &r);
        printf("Case #%d: %I64d\n", cas++, solve(d, l, r));
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值