题目描述
Alice and Bob have an integer N. Alice and Bob are not happy with their integer. Last night they went to a cocktail party and found that another couple had the exact same integer! Because of that they are getting a new integer.
Bob wants to impress the other couple and therefore he thinks their new integer should be strictly larger than N.
Alice herself is actually fond of some specific integer k. Therefore, Alice thinks that whatever integer they pick, it should be possible to write it as a sum of k distinct powers of 2.
Bob is also a cheapskate, therefore he wants to spend as little money as possible. Since the cost of an integer is proportional to its size, he wants to get an integer that is as small as possible.
输入
• A single line containing two integers N and k, with 1 ≤ N ≤ 1018 and 1 ≤ k ≤ 60.
输出
Output M, the smallest integer larger than N that can be written as the sum of exactly k distinct powers of 2.
样例输入
1 2
样例输出
3
来源/分类
题意:
给出一个数n, 求:比 n 大的 转化成二进制有 k 个1的最小的数; ans>n ans二进制中有 k 个1 求最小的ans。
分析:
对给出的 n 转成二进制 把其 1 个数量 n1 与 k 比较 :
- n1 < k :从低位填 1 ,填满 k 个1。
- n1 = k :将出现的第一个 1 前面的 0 变成1,剩下的低位清0,从低位开始将剩下的1填上。(具体看代码吧....)
- n1 > k :将低位的 1 清除 到剩下 k 个为止,转化成了上面第二种情况。
这个题.....写的很难受, 一开始的思路就是对的 然鹅....写到精神崩溃
还是太菜了,最近情绪也有些....emmm
调整心态吧
你赠予我的,我都装在心里。那么,祝你早安、午安、晚安。
PS:写的有点丑了也
#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
#define linf 0x3f3f3f3f3f3f3f3fLL
#define pi acos(-1.0)
#define ms(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
//ll qpow(ll x, ll y, ll mod){ll s=1;while(y){if(y&1)s=s*x%mod;x=x*x%mod;y>>=1;}return s;}
const int mod = 1e9+7;
ll qpow(ll a, ll b){ll s=1;while(b>0){if(b%2==1)s=s*a;a=a*a;b=b>>1;}return s;}
int main()
{
ll n; int k, num=0, n1=0;
int a[100], b[100];
scanf("%lld%d", &n, &k);
ll nn=n;
ms(a, -1);
while(nn){
a[num]=nn%2;
if(a[num]==1)
n1++;
num++;
nn/=2;
}
//reverse(a, a+num);
if(n1<k){
// for(int i=n1;i<=k;)
//{
//cout<<"132*-*-*-*-"<<endl;
int i=n1;
for(int j=0;i<k;j++)
{
if(a[j]==0){
a[j]=1;
i++;
}
if(a[j]==-1){
a[j]=1;
num++;
i++;
}
}
// }
}
if(n1>k){
for(int i=n1, j=0;i>k;j++)
{
if(a[j]==1){
i--;
a[j]=0;
}
}
n1=k;
}
if(n1==k){
int cnt1=0;
for(int i=0;;i++)
{
if(a[i]==1) cnt1++;
if(a[i]==1 && a[i+1]==0){
a[i+1]=1;
for(int j=i;j>=0;j--)
a[j]=0;
for(int j=0;j<cnt1-1;j++)
a[j]=1;
break;
}
if(a[i]==1 && a[i+1]==-1){
ms(a, 0), a[i+1]=1;
num++;
for(int j=0;j<k-1;j++)
a[j]=1;
break;
}
}
}
ll ans=0;
ll x = 1;
for(int i=0;i<num;i++)
ans+= (x<<i)*a[i];
printf("%lld\n", ans);
return 0;
}