C. Powers Of Two
time limit per test
4 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
A positive integer xx is called a power of two if it can be represented as x=2yx=2y , where yy is a non-negative integer. So, the powers of two are 1,2,4,8,16,…1,2,4,8,16,… .
You are given two positive integers nn and kk . Your task is to represent nn as the sum of exactly kk powers of two.
Input
The only line of the input contains two integers nn and kk (1≤n≤1091≤n≤109 , 1≤k≤2⋅1051≤k≤2⋅105 ).
Output
If it is impossible to represent nn as the sum of kk powers of two, print NO.
Otherwise, print YES, and then print kk positive integers b1,b2,…,bkb1,b2,…,bk such that each of bibi is a power of two, and ∑i=1kbi=n∑i=1kbi=n . If there are multiple answers, you may print any of them.
Examples
Input
Copy
9 4
Output
Copy
YES 1 2 2 4
Input
Copy
8 1
Output
Copy
YES 8
Input
Copy
5 1
Output
Copy
NO
Input
Copy
3 7
Output
Copy
NO
思路:
开个大小为k的数组,先把每个都填上1,之后设法把他们的和向n靠近,每次单个乘以2
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
int a[maxn];
int main()
{
int n,k;
scanf("%d %d",&n,&k);
int temp = k;
fill(a,a + k,1);
for (int i = 0;i < k;i ++)
{
while (temp + a[i] <= n)
{
temp += a[i];
a[i] *= 2;
}
}
if (temp != n) puts("NO");
else
{
printf("YES\n%d",a[k - 1]);
for (int i = k - 2;i >= 0;i --) printf(" %d",a[i]);
puts("");
}
return 0;
}