hdu5491 The Next 模拟

Let LL denote the number of 1s in integer DD’s binary representation. Given two integers S1S1 and S2S2, we call DD a WYH number if S1LS2S1≤L≤S2. 
With a given DD, we would like to find the next WYH number YY, which is JUST larger than DD. In other words, YY is the smallest WYH number among the numbers larger than DD. Please write a program to solve this problem. 

InputThe first line of input contains a number TT indicating the number of test cases (T300000T≤300000). 
Each test case consists of three integers DD, S1S1, and S2S2, as described above. It is guaranteed that 0D<2310≤D<231 and DD is a WYH number. 
OutputFor each test case, output a single line consisting of “Case #X: Y”. XX is the test case number starting from 1. YY 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

题目需要求的是比d大的且转化为二进制后1的个数在s1和s2之间的最小的数

开始想的是从d开始判断yi的个数分比s1小,在s1、s2之间(这里考虑的特别复杂),比s2大三种情况考虑,结果写了一大堆判断最后完美wa

后来在网上看别人的代码,是先让d+1,因为最后得到的数是比d大的,然后也是三种情况考虑,但是如果在s1、s2之间就可以直接输出,接着是比s1小则遇到0直接变成1,比s2大则遇到1变成0然后再一次进位

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<cmath>
#include<queue>
#define debug(a) cout << #a << " " << a << endl
using namespace std;
typedef long long ll;
int a[50], j;
ll sum() {
    ll ans = 0, t = 1;
    for( int i = 0; i <= 33; i ++ ) {
        ans = ans + a[i] * t;
        t *= 2;
    }
    return ans;
}
int main() {
    std::ios::sync_with_stdio(false);
    int T, cnt = 0;
    cin >> T;
    while( T -- ) {
        cnt ++;
        ll n, num = 0, x, y;
        j = 0;
        cin >> n >> x >> y;
        n ++;
        memset( a, 0, sizeof(a) );
        while( n ) {
            if( n % 2 == 1 ) {
                a[j++] = 1;
                num ++;
            } else {
                a[j++] = 0;
            }
            n /= 2;
        }
        while( 1 ) {
            if( num >= x && num <= y ) {
                cout << "Case #" << cnt << ": " << sum() << endl;
                break;
            }
            if( num < x ) {
                for( int i = 0; ; i ++ ) {
                    if( a[i] == 0 ) {
                        a[i] = 1;
                        num ++;
                        break;
                    }
                }
            } else {
                int i = 0;
                while( a[i] == 0 ) {
                    i ++;
                }
                a[i] ++;
                while( a[i] == 2 ) {
                    a[i] = 0;
                    num --;
                    a[i+1] ++;
                    i ++;
                }
                num ++;
            }
        }
    }
    return 0;
}

 

posted on 2018-05-09 11:06  九月旧约  阅读(197)  评论(0编辑  收藏  举报

导航