Codeforces Round #247 (D. Random Task)

題目

D. Random Taskios

time limit per testgit

1 seconddom

memory limit per testui

256 megabytesspa

inputssr

standard inputrest

outputcode

standard outputip

One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1n + 2, ..., 2·n there are exactly m numbers which binary representation contains exactly kdigits one".ci

The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.

Input

The first line contains two space-separated integers, m and k (0 ≤ m ≤ 10181 ≤ k ≤ 64).

Output

Print the required number n (1 ≤ n ≤ 1018). If there are multiple answers, print any of them.

Sample test(s)

input

1 1

output

1

input

3 2

output

5


解析

1.該題目數據量很大,所以須要注意數據的存儲類型防止越界,且徹底的暴力求解將會超時.

2.設範圍爲n+1~2n的數據中有k個1的數爲m,利用概括法可證得當n = n + 1時,有k個1的數據個數將會>=m, 呈現單調遞增性。所以可選用二分查找來加快速度。

3.n+1~2n的數據具備連續性能夠利用數位dp進一步縮短求解時間


解答

#include <iostream>
#include <cstring>

using namespace std;


#define CLR(a, val) memset(a, val, sizeof(a))


typedef long long int ll;

#define INF  1000000000000000000LL
#define MAXN 60LL

static void dp_init(void);
static ll dp_cnt(ll num);
static ll binary_search(ll start, ll end, ll needed);

ll m, k;
ll dp[70][70];

void dp_init(void){
    CLR(dp, 0);
    for(ll i = 0;  i <= MAXN; i++) 
        dp[i][0] = 1;
    for(ll i = 1;  i <= MAXN; i++){
        for(ll j = 1; j <= i; j++)
                dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1];
    }
}


ll dp_cnt(ll num){
    ll bit_found = 0;
    ll bit_cnt   = 0;
    for(ll i = MAXN; i >= 0; i--){
        if(num & ( 1LL << i)){
             ll j = k - bit_found;
             if(j < 0){              
                 /*we can make sure that no more nums could found after j < 0*/
                 break; 
             }            
             bit_cnt += dp[i][j];
             bit_found++;
        }   
    }
    return bit_cnt;
}



ll binary_search(ll start, ll end, ll needed){
    ll bit_cnt, mid;
    dp_init();
    while(start <= end){
        mid = (start + end)/2;
        bit_cnt = dp_cnt(mid*2) - dp_cnt(mid);
        if(bit_cnt < needed){
            start = mid + 1;
        }else if(bit_cnt > needed){
            end   = mid - 1;
        }else{
            return mid;
        }
    }
    return -1;
}


int main()
{
    ll mid = 1;
    cin >> m >> k;
    cout << binary_search(1, INF, m) << endl;
return 0;
}
相關文章
相關標籤/搜索