当前位置:网站首页>拆分整数为2的幂次项和 → 理解多重背包问题二进制优化的核心思想
拆分整数为2的幂次项和 → 理解多重背包问题二进制优化的核心思想
2022-08-10 15:25:00 【hnjzsyjyj】
【题目描述】
输入一个整数,输出为2的幂次项和的形式。
【输入样例】
26
【输出样例】
26=1+2+4+8+11
【算法分析】
理解了此题,就明白了多重背包问题的二进制优化的主要思想。
多重背包问题的二进制优化思想解析及题目详见 https://blog.csdn.net/hnjzsyjyj/article/details/126190151
为了方便说明问题,此处简述多重背包问题的二进制优化思想如下:
多重背包问题通常可转化成01背包问题求解。但若将每种物品的数量拆分成多个1的话,时间复杂度会很高,从而导致TLE。所以,需要利用二进制优化思想。即:一个正整数n,可以被分解成1,2,4,…,2^(k-1),n-2^k+1的形式。其中,k是满足n-2^k+1>0的最大整数。
例如,假设给定价值为2,数量为10的物品,依据二进制优化思想可将10分解为1+2+4+3,则原来单个价值为2,数量为10的物品可等效转化为价值分别为1*2,2*2,4*2,3*2,即价值分别为2,4,8,6,数量均为1的物品。
.
【算法代码一】
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin>>n;
cout<<n<<"=";
int k=1;
while(k<=n) {
if(k==n) cout<<k;
else cout<<k<<"+";
n=n-k;
k=k*2;
}
if(n>0) {
cout<<n;
}
return 0;
}
/*
in1:
26
out1:
26=1+2+4+8+11
in2:
7
out2:
7=1+2+4
*/
【算法代码二】
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin>>n;
cout<<n<<"=";
int t=0;
int k=1;
while(k<=n) {
if(k==n) cout<<"2^"<<t;
else cout<<"2^"<<t<<"+";
n=n-k;
k=k*2;
t++;
}
if(n>0) {
cout<<n;
}
return 0;
}
/*
in1:
26
out1:
26=2^0+2^1+2^2+2^3+11
in2:
7
out2:
7=2^0+2^1+2^2
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/126190151
边栏推荐
- Recommend a few had better use the MySQL open source client, collection!
- $'\r': command not found
- Containerization | Scheduled Backups in S3
- web安全入门-Kill Chain测试流程
- 关于Web渗透测试需要知道的一切:完整指南
- Detailed understanding of all built-in functions (Part 2)
- FFmpeg 交叉编译
- 社区动态——恭喜海豚调度中国区用户组新晋 9 枚“社群管理员”
- How to code like a pro in 2022 and avoid If-Else
- 消息称原美图高管加盟蔚来手机 顶配产品或超7000元
猜你喜欢
Cesium Quick Start 4-Polylines primitive usage explanation
企业如何开展ERP数据治理工作?_光点科技
全志V853开发板移植基于 LVGL 的 2048 小游戏
Colocate Join :ClickHouse的一种高性能分布式join查询模型
SWIG tutorial "two"
fatal error C1083 Unable to open include file 'io.h' No such file
QOS function introduction
关于“算力”,这篇文章值得一看
一个 ABAP Development Tool 自定义 service endpoint 的测试工具
E. Cross Swapping (and check out deformation/good questions)
随机推荐
NPM - Cannot read properties of null (reading 'pickAlgorithm') 解决方案
Mobileye携手极氪通过OTA升级开启高级驾驶辅助新篇章
关于async\await 的理解和思考
【每日一题】【leetcode】25. 数组-旋转数组的最小数字
"NIO Cup" 2022 Nioke Summer Multi-School Training Camp 7
Colocate Join :ClickHouse的一种高性能分布式join查询模型
metaForce佛萨奇2.0系统开发功能逻辑介绍
MySQL-创建、修改和删除表
Understanding_Data_Types_in_Go
Brainstorm: Goals and
FP6378AS5CTR SOT - 23-5 effective 1 mhz2a synchronous buck regulator
第壹章模块大全之《re模块》
一个 ABAP 工具,能打印系统里某个用户对 BSP 应用的浏览历史记录
Based on Azuki Series: NFT Valuation Analysis Framework "DRIC"
A Sina Weibo semantic sentiment analysis tool developed by ABAP
消息称原美图高管加盟蔚来手机 顶配产品或超7000元
$'\r': command not found
产品说明丨如何使用MobPush快速创建应用
颜色空间
头脑风暴:目标和