Codeforces-916B:Jamie and Binary Sequence (changed after round)(思維)
Jamie is preparing a Codeforces round. He has got an idea for a problem, but does not know how to solve it. Help him write a solution to the following problem:
Find k integers such that the sum of two to the power of each number equals to the number n and the largest integer in the answer is as small as possible. As there may be multiple answers, you are asked to output the lexicographically largest one.
To be more clear, consider all integer sequence with length k (a1, a2, ..., ak) with . Give a value to each sequence. Among all sequence(s) that have the minimum y value, output the one that is the lexicographically largest.
For definitions of powers and lexicographical order see notes.
Input
The first line consists of two integers n
Output "No" (without quotes) in a single line if there does not exist such sequence. Otherwise, output "Yes" (without quotes) in the first line, and k numbers separated by space in the second line — the required sequence.
It is guaranteed that the integers in the answer sequence fit the range [ - 1018, 1018].
Examples input23 5output
Yes 3 3 2 1 0input
13 2output
Noinput
1 2output
Yes -1 -1Note
Sample 1:
23 + 23 + 22 + 21 + 20 = 8 + 8 + 4 + 2 + 1 = 23
Answers like (3, 3, 2, 0, 1) or (0, 1, 2, 3, 3) are not lexicographically largest.
Answers like (4, 1, 1, 1, 0) do not have the minimum y value.
Sample 2:
It can be shown there does not exist a sequence with length 2.
Sample 3:
Powers of 2:
If x > 0, then 2x = 2·2·2·...·2 (x times).
If x = 0, then 2x = 1.
If x < 0, then .
Lexicographical order:
Given two different sequences of the same length, (a1, a2, ... , ak) and (b1, b2, ... , bk), the first one is smaller than the second one for the lexicographical order, if and only if ai < bi, for the first i where ai and bi differ.
思路:我們可以先將n轉化為二進位制數,然後把高位的1轉化低位的2個1,來滿足總共有k個1。因為要保證最高位越小越好,一開始就不斷從高位向低位轉化。若再轉化,1的個數將大於k時,就從低位開始一個一個轉化,使得字典序儘量大。#include<bits/stdc++.h>
using namespace std;
const int MAX=1e6;
const int MOD=1e9+7;
typedef __int64 ll;
ll p[100],f[MAX];//f[i]表示2^(-i);
int main()
{
ll n,k,res=1;
cin>>n>>k;
int len=0,last=0;
while(n)p[len++]=n%2,n/=2;
for(int i=0;i<len;i++)k-=p[i];
if(k<0){puts("No");return 0;}//1的個數一開始就大於k
for(int i=len-1;;i--)
{
if((i>=0&&p[i]==0)||(i<0&&f[-i]==0))continue;
if((i>=0&&p[i]>k)||(i<0&&f[-i]>k))break;//再轉化,1的個數將大於k
if(i>0)
{
p[i-1]+=2*p[i];
k-=p[i];
p[i]=0;
}
if(i==0)
{
f[1]+=2*p[i];
k-=p[i];
p[i]=0;
last=1;
}
if(i<0)
{
f[-(i-1)]+=2*f[-i];
k-=f[-i];
f[-i]=0;
last=-(i-1);
}
}
while(k)
{
for(int i=last;i>0;i--)//從低位開始
{
if(f[i]==0)continue;
k--;//一個一個的轉化
f[i]--;
f[i+1]+=2;
last=i+1;
goto nex;
}
if(p[0])
{
k--;
p[0]--;
f[1]+=2;
last=1;
continue;
}
for(int i=1;i<len;i++)
{
if(p[i]==0)continue;
k--;
p[i]--;
p[i-1]+=2;
goto nex;
}
nex:;
}
puts("Yes");
for(int i=len-1;i>=0;i--)while(p[i]>0&&p[i]--)printf("%d ",i);
for(int i=1;i<=last;i++)while(f[i]>0&&f[i]--)printf("%d ",-i);
return 0;
}