首页 技术 正文
技术 2022年11月12日
0 收藏 507 点赞 4,606 浏览 980 个字

二进制优化,事实上是物体的分解问题。

就是比方一个物体有数量限制,比方是13,那么就须要把这个物体分解为1。 2, 4, 6

假设这个物体有数量为25,那么就分解为1, 2, 4。 8。 10

看出规律吗,就是分成2的倍数加上位数,比方6 = 13 – 1 – 2 – 4, 10 = 25 – 1 – 2 – 4 – 8。呵呵,为什么这么分解?

由于这样分解之后就能够组合成全部1到13的数。为25的时候能够组合成全部1到25的数啦。

就是这么一个分解物体。最后组合的问题。

不明确?

给多几个数字组合:

31分解 1, 2, 4, 8, 16

32分解1,2,4, 8, 16, 1

33分解1,2,4,8,16,2

如此分解的。

想通了,就和一般背包问题一样做法了。

#include <stdio.h>
#include <vector>
using std::vector;const int SIZE = 7;
int N[SIZE];
bool findPartition()
{
int sum = 0;
for (int i = 1; i < SIZE; i++)
sum += i * N[i];
if (sum & 1) return false;int half = sum >> 1;
vector<bool> part(half+1);
part[0] = true;for (int i = 1; i < SIZE; i++)
{
int k = 1;
for ( ; (k<<1) <= N[i]; k <<= 1)
{//例:13分解为1,2,4,6能够组合为1到13个物品。故此考虑了全部情况了
for (int j = half; j >= k*i; j--)
{
if (part[j-k*i]) part[j] = true;
}
}
k = N[i] - k + 1;
for (int j = half; j >= k*i; j--)
{
if (part[j-k*i]) part[j] = true;
}
}
return part[half];
}int main()
{
int t = 1;
while (true)
{
int val = 0;
for (int i = 1; i < SIZE; i++)
{
scanf("%d", &N[i]);
val += N[i];
}
if (!val) return 0;
if (findPartition()) printf("Collection #%d:\nCan be divided.\n\n", t++);
else printf("Collection #%d:\nCan't be divided.\n\n", t++);
}
return 0;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,564
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,413
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,186
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905