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 S1≤L≤S2.
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.
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 (T≤300000).
Each test case consists of three integers D, S1, and S2, as described above. It is guaranteed that 0≤D<231 and D is a WYH number.
Each test case consists of three integers D, S1, and S2, as described above. It is guaranteed that 0≤D<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);
}
}