hdu 5491 The Next(暴力枚举)

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.
 
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, S1, and S2, as described above. It is guaranteed that ≤D< 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 . Y is the next WYH number.
Sample Input

 
Sample Output
Case #:
Case #:
Case #:
 
Source
 

不想写,找了个别人的.

思路:

考虑通过比较当前的1的数目来进行最小的数的修正。

先将D加1,然后计算出D的1的数目tot,这时候比较tot和s1,s2的大小,这时候有两种情况:

1、tot<s1,这时我需要增加1的数目,因为要最小,所以我从右开始找到一个0(位置假设为i),将D加上2^i。

2、tot>s2,这时我需要减少1的数目,所以我从右开始找到一个1,将D加上2^i。

如此循环上述过程,直到符合tot符合s1,s2的条件。

上面操作的原因是:我加上2^i,就是将那一位由1变为0或者由0变为1,而我是从右边开始寻找的,可以保证每次所做的改变都是最小的。同时我的D是一直增加的,所以当条件满足时,就是那个最小的。

 #pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
#include<bitset>
#include<map>
#include<vector>
#include<stdlib.h>
#include <stack>
using namespace std;
int dirx[]={,,-,};
int diry[]={-,,,};
#define PI acos(-1.0)
#define max(a,b) (a) > (b) ? (a) : (b)
#define min(a,b) (a) < (b) ? (a) : (b)
#define ll long long
#define eps 1e-10
#define MOD 1000000007
#define N 100
#define inf 1e12
ll d,s1,s2;
ll num[N];
ll k;
ll count_(ll dd){
memset(num,,sizeof(num));
ll cnt=;
k=;
while(dd){
if(dd&) cnt++;
num[k++]=(dd&);
dd>>=;
}
num[k++]=; return cnt;
}
int main()
{
ll ac=;
ll t;
scanf("%I64d",&t);
while(t--){
scanf("%I64d%I64d%I64d",&d,&s1,&s2); ll dd=d+; while(){
ll tmp=count_(dd); if(tmp<s1){
for(ll i=;i<k;i++){
if(num[i]==){
dd+=(<<i);
break;
}
}
}else if(tmp>s2){
for(ll i=;i<k;i++){
if(num[i]==){
dd+=(<<i);
break;
}
}
}else{
break;
}
}
printf("Case #%I64d: ",++ac);
printf("%I64d\n",dd); }
return ;
}
上一篇:Qt文件信息获取之QFileInfo


下一篇:SQL Server 查询某一个数据库存储过程、函数是否包含某一个内容或者脚本