问题 E: Envious Exponents
时间限制: 1 Sec 内存限制: 128 MB
提交: 334 解决: 58
[提交] [状态] [讨论版] [命题人:admin]
题目描述
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表示为2^xi的和,x为k个不同的数;
思路:将n表示成2进制数,统计含有的1的个数为cnt,与k进行比较
(1)cnt>k 转换为cnt1=k的情况处理,即将低位多的1清为0
(2)cnt=k 将第一个非前置0变成1,剩下的低位清0,从低位开始将剩下的1填上
(3)cnt<k 直白的操作,从低位开始填1
最后将二进制转换回来,不爆long long
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
ll n;
int k;
scanf("%lld%d",&n,&k);
int a[110]={0};
int i=0,cnt=0;
while(n)
{
a[i++]=n%2;
if(n%2==1)
cnt++;
n=n/2;
}
if(cnt>k)
{
for(int j=0;j<i;j++)
{
if(a[j]==1)
{
a[j]=0;
cnt--;
}
if(cnt==k)
break;
}
}
if(cnt==k)
{
int flag=0;
int cnt1=0;
int k=0;
while(flag==0||a[k]==1)
{
if(a[k]==1)
{
cnt1++;
flag=1;
}
k++;
}
a[k]=1;
cnt1--;
for(i=0;i<k;i++)
{
if(cnt1)
{
a[i]=1;
cnt1--;
}
else
a[i]=0;
}
}
if(cnt<k)
{
for(i=0;;)
{
if(a[i]==0)
{
a[i]=1;
cnt++;
}
i++;
if(cnt==k)
break;
}
}
ll ans=0;
ll x=1;
for(int j=0;j<100;j++)
{
if(a[j])
ans+=x;
x=x*2;
}
printf("%lld\n",ans);
return 0;
}