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 + 1, n + 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 ≤ 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; }