Codeforces 1095C. Powers Of Two——————multiset
C. Powers Of Two
A positive integer x is called a power of two if it can be represented as , where y is a non-negative integer. So, the powers of two are 1,2,4,8,16,….
You are given two positive integers n and k. Your task is to represent n as the sum of exactly k powers of two.
Input
The only line of the input contains two integers n and k (1≤n≤1e9, 1≤k≤2⋅1e5).
Output
If it is impossible to represent n as the sum of k powers of two, print NO.
Otherwise, print YES, and then print k positive integers such that each of bi is a power of two, and . If there are multiple answers, you may print any of them.
Examples
input
9 4
output
YES
1 2 2 4
input
8 1
output
YES
8
input
5 1
output
NO
input
3 7
output
NO
题目就是说,给你n和k,让你用k个,使得,根据样例可以知道,可以使重复的。
我们可以知道,对于任何一个正整数,都可以将其写成二进制的加法形式。比如
,
此时k = 2,但是我们可以将分解为
于是k = 3,此时,在将大的分解
于是k = 4,此时,符合题意,输出
是一种某个数可以重复出现的集合,它通常以平衡二叉树完成.
#include<bits/stdc++.h>
// #define SUBMIT
using namespace std;
typedef long long ll;
int main()
{
#ifdef SUBMIT
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
ll _begin_time = clock();
#endif
int n,k;
multiset<int> s;
cin>>n>>k;
int m = n;
for(int i=0;m;m>>=1,i++) if(m&1) s.insert(1<<i);
// for(multiset<int>::iterator it=s.begin();it!=s.end();++it)
// cout<<*it<<" ";
// cout<<endl;
if(n<k||s.size()>k) cout<<"NO"<<endl;
else
{
while(s.size()<k)
{
int a = *(--s.end()); s.erase(--s.end());
if(a==1) break;
s.insert(a/2);
s.insert(a/2);
}
cout<<"YES"<<endl;
while(s.size())
{
cout<<*s.begin()<<" ";
s.erase(s.begin());
}
cout<<endl;
}
#ifdef SUBMIT
ll _end_time = clock();
printf("Time: %I64d ms\n",_end_time - _begin_time);
#endif
return 0;
}