CF 1095C Powers Of Two
题目连接:http://codeforces.com/problemset/problem/1095/C
题目:
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 twoare 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
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
的2的幂的数列,使得
思路:看到对于2的指数形式,首先要想到其中一个方法——将该数字换算成2进制。
该题正好可以。接着从最高位一步一步拆(03101001
sum=6
→ 02301001
sum=7
→ 01501001
sum=8
)
代码中有更为详细的注解。
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int n,k;
int s[105];//储存二进制数,且储存方式为低位在前,高位在后;
int main()
{
scanf("%d %d",&n,&k);
int x=n,sum=0;
int t;//记录转换为二进制数的位数
for(t=0;x!=0;)
{
s[++t]=x&1;
x/=2;
if(s[t])
sum+=1;//记录二进制数中1的个数
}
/*开始写的时候在考虑 转换成二进制要进行拆分几次?如何判断?
下面的循环体 就是判断条件 sum<k时肯定不符合题意,从最高位
一次一次拆分,直到1的个数等于或大于k跳出循环体*/
while(sum<k)
{
if(t==1)
break;
/*从最高位开始拆分,最高位-1,次高位加2,
如果一直不能跳出循环,则换算成的二进制经过拆分,
又回到了初始情况n,此时位数t为1,跳出循环*/
s[t]-=1; s[t-1]+=2;
if(!s[t])
t-=1;
sum+=1;
}
if(sum!=k)
{
puts("NO");return 0;
}
else
{
puts("YES");
int T=1;
for(int i=1;i<t;i++,T*=2)
{
for(int j=1;j<=s[i];j++)
printf("%d ",T);
}
for(int i=1;i<s[t];i++)
printf("%d ",T);
printf("%d\n",T);
return 0;
}
}
最新文章
- Redis 缓存过期(maxmemory) 配置/算法 详解
- 教你一招:在PowerPoint中自定义可输入文本的占位符
- Java泛型学习笔记 - (四)有界类型参数
- 线程的Abort方法有感
- ecshop订单-》待付款,待发货,待收货,收货确认
- Mayor&#39;s posters(线段树+离散化POJ2528)
- sqlserver数据库学习(-)数据类型
- MRD
- openwrt 编译newifi 应用程序
- Populating Next Right Pointers in Each Node [LeetCode]
- JS实现 页面提交防刷新等待提示
- 自己写的SqlHelper
- kafka配额控制
- XML中 添加或修改时 xmlns=";"; 怎么删除
- PHP设置http头信息
- MEMS市场介绍
- 函数调用过程&;生成器解释
- 一个想法照进现实-《IT连》创业项目:一个转折一个反思
- 百度插件webuploader的坑!
- iOS积分抽奖Demo,可以人为控制不同奖项的得奖率
热门文章
- Django实现websocket
- P 1024 科学计数法
- vue坑 - vue安装vue-cli报错coffee-script@1.12.7: CoffeeScript on NPM has moved to ";coffeescript"; (no hyphen)或者说不支
- EUI库 - 快速入口之项目配置
- jQuery搜索框输入实时进行查询
- SpringBoot之Order注解启动顺序
- Win7 node多版本管理gnvm采坑记录
- Java TCP发送与接收
- 澳洲Essay写作常见误区汇总
- python脚本下载 Google Driver 文件