2015年ACM-ICPC亚洲区域赛合肥站网络预选赛H题——The Next (位运算)

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


输入要求

The first line of input contains a number T indicating the number of test cases (T≤100000).
Each test case consists of three integers D, S1, and S2, as described above. It is guaranteed that 0≤D<2^28 and D is a XHY number.

输出要求

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 XHY number.

测试数据示例

输入

3
11 2 4
22 3 3
15 2 5

输出

Case #1: 12
Case #2: 25
Case #3: 17
 
大水题,开始以为会TLE,结果暴力搞一下位运算就过了,主要是题目有难懂。
 
题目意思大概如下:
L代表整数D的二进制位为1的个数。譬如D=3,L=2。
假如s1<=L<=s2,则D就是XHY数。现在就是要你找出大于D的最小XHY数。
 
题目明白了之后就是很裸的按位与(&)操作。
 
上代码了.
C code
 
#include <stdio.h>

int slove(int d,int s1,int s2){
    int next;
    long end =  1 << 28;
    for(int i=d+1;i<=end;i++){
        int bitCount = 0;
        for(int j=0;j<31;j++){
            if( (i & (1<<j)) > 0) bitCount++;
        }
        if(bitCount>=s1 && bitCount <= s2){
           next=i;
           break;
        }
    }
    return next;
}
int main(){
    int n;
    int d;
    int s1;
    int s2;
    int c = 1;
    while(scanf("%d",&n)==1){
        for(int i=0;i<n;i++){
            scanf("%d",&d);
            scanf("%d",&s1);
            scanf("%d",&s2);
            int ret = slove(d,s1,s2);
            printf("Case #%d: %d\n",c++,ret);
        }
    }
}

 

 
 
posted @ 2016-04-13 14:09  hudiwei-hdw  阅读(299)  评论(0编辑  收藏  举报