HDU 5491 The Next
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5491
The Next
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1118 Accepted Submission(s): 446
Problem Description
Let L denote the number of 1s in integer D’s binary representation. Given two integers S and S, we call D a WYH number if S.
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).
Each test case consists of three integers D, S, and S, as described above. It is guaranteed that 0≤D<231 and D is a WYH number.
Each test case consists of three integers D, S, and S, 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
题目大意是给你一个数,让你找到一个比它大的数且转换为二进制后1的个数在给定的范围内。
这个题比较简单,就是对0-1串进行处理,先把给定的数加一,保证结果比给定的数大,然后分两种情况,1的个数太少则从低位起遇到第一个0改成1;1的个数太多则从低位起遇到第一个1加1,然后向前进位。这样能保证结果是递增的,当1的个数满足条件是即是最后的结果。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <cstring> 3 #include <algorithm> 4 using namespace std; 5 6 long long ans,t,n,nu,mi,ma,c[50],j,s; 7 long long fina() 8 { 9 long long sum=c[0],te=1; 10 for (int i=1;i<=33;i++) 11 { 12 te*=2; 13 sum=sum+te*c[i]; 14 } 15 return sum; 16 } 17 int main() 18 { 19 20 //cin>>t; 21 scanf("%lld",&t); 22 for (int cas=1;cas<=t;cas++) 23 { 24 //cin>>nu>>mi>>ma; 25 scanf("%lld%lld%lld",&nu,&mi,&ma); 26 nu++; 27 ans=nu; 28 memset(c,0,sizeof(c)); 29 j=0,s=0; 30 while (nu!=0) 31 { 32 if (nu%2) 33 s++; 34 c[j++]=nu%2; 35 nu/=2; 36 } 37 j--; 38 while (1) 39 { 40 if (s>=mi&&s<=ma) 41 { 42 43 //cout <<"Case #"<<cas<<": "<<fina()<<endl; 44 printf("Case #%d: %lld\n",cas,fina()); 45 break; 46 } 47 if (s<mi) 48 { 49 for (int i=0;;i++) 50 { 51 if (c[i]==0) 52 { 53 c[i]=1; 54 s++; 55 break; 56 } 57 } 58 } 59 else 60 { 61 int i=0; 62 while (c[i]==0) 63 i++; 64 c[i]++; 65 while (c[i]==2) 66 { 67 c[i]=0; 68 s--; 69 c[i+1]++; 70 i++; 71 } 72 s++; 73 } 74 } 75 } 76 return 0; 77 }