A positive integer x is called a power of two if it can be represented as x = 2^y, 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 nn and k (1≤n≤109,1≤k≤2⋅105).
Output
If it is impossible to represent nn as the sum of k powers of two, print NO.
Otherwise, print YES, and then print k positive integers b1,b2,…,bk such that each of b_ibi is a power of two, and ni=1∑kbi=n. If there are multiple answers, you may print any of them.
Sample 1
Inputcopy | Outputcopy |
---|---|
9 4 | YES 1 2 2 4 |
Sample 2
Inputcopy | Outputcopy |
---|---|
8 1 | YES 8 |
Sample 3
Inputcopy | Outputcopy |
---|---|
5 1 | NO |
Sample 4
Inputcopy | Outputcopy |
---|---|
3 7 | NO |
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 2e5 + 5; // 最大数组大小
int n, k; // 输入的整数n和k
int main() {
cin >> n >> k; // 输入n和k
if (n < k) { // 如果n小于k,无法满足要求
cout << "NO" << endl;
return 0;
}
vector<int> vec(k, 1); // 创建一个大小为k的vector,初始值都为1
n -= k; //保证至少又k个数字可用于构造
for (int i = 0; i < k; ++i) {
while (vec[i] <= n) { // 当前位置的数字还可以翻倍时,继续翻倍直到不满足条件
n -= vec[i]; // 减去已经使用的数字数量
vec[i] *= 2; // 将当前位置的数字翻倍
}
}
if (n) { // 如果仍然有剩余的数字没有使用完,则无法满足要求
cout << "NO" << endl;
}
else { // 否则可以满足要求
cout << "YES" << endl;
for (int i = 0; i < k; ++i) {
cout << vec[i] << (i == k - 1 ? '\n' : ' '); // 输出结果,最后一个数字后面换行,其他数字后面加空格
}
}
return 0;
}