The Next
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 305 Accepted Submission(s): 137
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 $S_1leq Lleq S_2$.
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 $(Tleq 300000)$.
Each test case consists of three integers D, S1, and S2, as described above. It is guaranteed that $0leq D < 2^{31}$ and D is a WYH number.
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long LL; 4 inline int lowbit(int x){ 5 return x&-x; 6 } 7 int main(){ 8 int kase,cs = 1,S1,S2; 9 LL D; 10 scanf("%d",&kase); 11 while(kase--){ 12 scanf("%I64d%d%d",&D,&S1,&S2); 13 LL ret = D + 1,lb = lowbit(ret); 14 int cnt = __builtin_popcount(ret); 15 while(cnt < S1 || cnt > S2){ 16 int tmp = __builtin_popcount(lb - 1); 17 if(S1 > cnt + tmp|| cnt > S2){ 18 ret += lb; 19 lb = lowbit(ret); 20 cnt = __builtin_popcount(ret); 21 }else{ 22 int t = max(cnt,S1) - cnt; 23 ret += (1<<t) - 1; 24 break; 25 } 26 } 27 printf("Case #%d: %I64d ",cs++,ret); 28 } 29 return 0; 30 }