Codeforces Round #247 (Div. 2) D. Random Task

来源:互联网 发布:农行网银mac版 编辑:程序博客网 时间:2024/06/03 19:40
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 + 1n + 2, ..., n there are exactly m numbers which binary representation contains exactlyk digits 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 ≤ 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


假如我们知道答案ans,那只需要统计ans+1~2*ans之间满足条件的数,用dp[i][j]表示前i位二进制有j个1的数的个数,剩下的就是套模板了==
a+1~2*a中满足条件的数<m,那么a~2(a-1)肯定也<m;

#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;#define clr(a) memset(a,-1,sizeof(a));typedef long long ll;const ll MAXN=1000000000000000000LL;ll dp[70][70],m;int bit[70],len,k;inline ll dfs(int i,bool e,int num){    if(i<0){        return num==k;    }    if(!e && dp[i][num]!=-1) return dp[i][num];    ll ans=0;    int v=(e?bit[i]:1);    for(int j=0;j<=v;j++){        ans+=dfs(i-1,e&&(j==v),num+(j==1));    }    if(!e) dp[i][num]=ans;    return ans;}inline ll solve(ll n){    len=0;    while(n){        bit[len++]=n%2;        n>>=1;    }    return dfs(len-1,1,0);}int main(){        while(~scanf("%I64d%d",&m,&k)){        ll l=1,r=MAXN;clr(dp);        while(l<=r){            ll mid=l+(r-l)/2LL;            ll sum=solve(mid*2)-solve(mid);            if(sum==m){                l=mid;break;            }            else if(sum<m){                l=mid+1;            }            else r=mid-1;        }        printf("%I64d\n",l);    }    return 0;}




0 0