码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-04-13 14:33:30      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

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, Y 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);
        }
    }
}

 

 
 

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

标签:

原文地址:http://www.cnblogs.com/dick159/p/5386951.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!