CF 1095C Powers Of Two(二進制拆分)
阿新 • • 發佈:2019-03-10
con hat 會有 inpu += string may pre ace
Output
If it is impossible to represent nn as the sum of k powers of two, print NO.
Otherwise, print YES, and then print kk positive integers b1,b2,…,bk such that each of bibi is a power of two, and ∑i=1kbi=n. 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
題目意思:給定一個數,讓你用1,2,4,8等2的倍數表示出來,並且要用指定的k個數,輸出一種即可。
A positive integer xx is called a power of two if it can be represented as x=2y, where y is a non-negative integer. So, the powers of two are 1,2,4,8,16,…
You are given two positive integers nn and k. Your task is to represent nn as the sumof 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 kk positive integers b1,b2,…,bk such that each of bibi is a power of two, and ∑i=1kbi=n. If there are multiple answers, you may print any of them.
Examples
Input
9 4
Output
YES
Input
8 1
Output
YES
8
Input
5 1
Output
NO
Input
3 7
Output
NO
題目意思:給定一個數,讓你用1,2,4,8等2的倍數表示出來,並且要用指定的k個數,輸出一種即可。
解題思路:我們知道任意一個數都可以通過2的倍數組成,這其中的原因可以通過十進制轉換二進制來說明。
如果該數的二進制對應數中1的個數大於k,那麽很顯然不會有k個2的倍數組成該數;如果恰好相等,那麽只需要將二進制各個位上的1轉換為對應的十進制即可;如果該數的二進制對應數中1的個數小於k,那麽就需要拆分二進制了,這裏我從高位來開始拆分,每當高位-1時,對應的下一位將會+2,這裏存放二進制的數組裏將不再僅僅存放0和1了,這時候存放的是對應二進制位數的個數了,只要拆分到恰夠k個即可。同時要註意pow函數的使用,這個函數返回值是double類型的,註意轉換。
#include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; int main() { int n,k,counts,i,j,x,y,a,ans; int b[110]; scanf("%d%d",&n,&k); counts=0; x=0; a=n; while(a) { if(a%2) { counts++; } b[x]=a%2; x++; a/=2; } //printf("%d\n",counts); //printf("%d\n",x); if(k<counts||k>n)///不滿足條件的情況 { printf("NO\n"); } else { printf("YES\n"); if(counts==k)///直接按照進制,不需要拆分 { for(i=0; i<x; i++) { if(b[i]) { ans=int(pow(2,i)); printf("%d ",ans); } } } else///即k>counts,從高位開始拆分,高位-1,相當於低位+2,counts+1 { y=x-1;///最高位 while(counts!=k)///終止條件 { while(b[y]>=1) { b[y]--; b[y-1]+=2; counts++; if(counts==k) { break; } } y--; } for(i=x-1; i>=0; i--)///輸出 { if(b[i]>=1)///註意這裏b[i]上的值代表的是該位上對應2^i的個數 { for(j=0; j<b[i]; j++) { ans=int(pow(2,i)); printf("%d ",ans); } } } } } return 0; }
CF 1095C Powers Of Two(二進制拆分)