Hdu 5491 The Next【贪心+lowbit】

本文介绍了一道算法题,任务是找出大于给定整数D的下一个整数Y,该整数的二进制表示中1的数量位于指定范围内。文章提供了解题思路及AC代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The Next

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2184    Accepted Submission(s): 800


Problem Description
Let L denote the number of 1s in integer D’s binary representation. Given two integers S1 and S2, we call D a WYH number if S1LS2.
With a given D, we would like to find the next WYH number Y, which is JUST larger than D. In other words, Y is the smallest WYH number among the numbers larger than D. Please write a program to solve this problem.
 

Input
The first line of input contains a number T indicating the number of test cases (T300000).
Each test case consists of three integers DS1, and S2, as described above. It is guaranteed that 0D<231 and D is a WYH number.
 

Output
For each test case, output a single line consisting of “Case #X: Y”. X is the test case number starting from 1. Y is the next WYH number.
 

Sample Input
3 11 2 4 22 3 3 15 2 5
 

Sample Output
Case #1: 12 Case #2: 25 Case #3: 17

题目大意:


给你一个数D,再给你两个数S1,S2,设定L表示的是数字D在二进制表示下,1的个数。

问比D大的数Num,使得其满足:S1<=L<=S2的数字是多少。


思路:


①一开始我们可以设定Ans=D+1.那么我们判断Ans的L是多少,如果在【S1,S2】之间的话,直接输出这个Ans即可。否则我们考虑将1的个数进行调整。

②如果存在L>S2,那么我们明显想要去掉1的个数,而且希望尽量去去掉位低的1,而我们去除1的方法只有将Ans增大这一种方法,所以我们考虑找到Ans的最后一个1所在的位子,然后将Ans加上(1<<pos)即可。我们可以用lowbit加速查找。

③如果存在L<S1,那么我们明显想要加1的个数,同时希望增加的1在低位,那么我们从后向前找最低的0的位子,然后将Ans加上(1<<pos)即可。


Ac代码:

#include<stdio.h>
#include<string.h>
using namespace std;
#define ll long long int
ll lowbit(ll num)
{
    return num&(-num);
}
int main()
{
    int kase=0;
    int t;
    scanf("%d",&t);
    while(t--)
    {
        ll num;
        int s1,s2;
        scanf("%lld%d%d",&num,&s1,&s2);
        num++;
        while(1)
        {
            int cnt=0;
            ll tmp=num;
            while(tmp)tmp-=lowbit(tmp),cnt++;
            if(cnt>=s1&&cnt<=s2)break;
            else
            {
                if(cnt>s1)
                {
                    num+=lowbit(num);
                }
                else
                {
                    for(int i=0;i<=31;i++)
                    {
                        if(((1<<i)&num)==0)
                        {
                            num+=(1<<i);
                            break;
                        }
                    }
                }
            }
        }
         printf("Case #%d: %lld\n",++kase,num);

    }
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值