您的位置:首页 > 其它

Codeforces Round #247 (D. Random Task)

2014-06-06 00:00 176 查看
摘要: Codeforces Round #247 (D. Random Task)

题目

D. Random Task
time limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard output

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 + 1, n + 2, ..., 2·n there are exactly m numbers which binary representation contains exactly kdigits one".
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 ≤ 1018; 1 ≤ 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  codefoeces acm