生成列表的电源集
Generating the power set of a list
我必须编写背包问题的暴力实现。这是伪代码:
computeMaxProfit(weight_capacity)
max_profit = 0
S = {} // Each element of S is a weight-profit pair.
while true
if the sum of the weights in S <= weight_capacity
if the sum of the profits in S > max_profit
update max_profit
if S contains all items // Then there is no next subset to generate
return max
generate the next subset S
虽然该算法很容易实现,但我完全不知道如何生成S的幂集,以及如何将幂集的子集输入While循环的每次迭代。
我目前的实现使用一个成对的列表来保持物品的重量和利润:
list< pair<int, int> > weight_profit_pair;
我想为我的computeMaxProfit函数生成这个列表的幂集。有没有一种算法可以生成列表的子集?列表是正确的容器吗?
这里有两个函数可以完成任务:
// Returns which bits are on in the integer a
vector<int> getOnLocations(int a) {
vector<int> result;
int place = 0;
while (a != 0) {
if (a & 1) {
result.push_back(place);
}
++place;
a >>= 1;
}
return result;
}
template<typename T>
vector<vector<T> > powerSet(const vector<T>& set) {
vector<vector<T> > result;
int numPowerSets = static_cast<int>(pow(2.0, static_cast<double>(set.size())));
for (size_t i = 0; i < numPowerSets; ++i) {
vector<int> onLocations = getOnLocations(i);
vector<T> subSet;
for (size_t j = 0; j < onLocations.size(); ++j) {
subSet.push_back(set.at(onLocations.at(j)));
}
result.push_back(subSet);
}
return result;
}
numPowerSets
使用了Marcelo在这里提到的关系。正如LiKao所提到的,矢量似乎是一种自然的方式。当然,不要用大套试试这个!
不要使用列表,而是使用任何类型的随机访问数据结构,例如std::vector
。如果您现在有另一个std::vector<bool>
,您可以将这两个结构一起使用来表示幂集的一个元素。即,如果位置x
处的bool
为真,则位置x
处的元素在子集中。
现在,您必须对幂集中的所有集合进行迭代。也就是说,你必须从每个当前子集生成下一个子集,这样所有的集合都会生成。这只是std::vector<bool>
上的二进制计数。
如果集合中的元素少于64个,则可以使用长整数进行计数,并在每次迭代时获得二进制表示。
数字集S={0,1,2,…,2n-1}形成比特集{1,2,4,…,2*sup>n-1}的幂集。对于集合S中的每个数字,通过将数字的每个位映射到集合中的一个元素来导出原始集合的子集。由于对所有64位整数进行迭代是很困难的,因此您应该能够在不使用bigint库的情况下完成此操作。
相关文章:
- Pybind11:将元组列表从Python传递到C++
- 从链接列表c++中删除一个项目
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- C++如何通过用户输入删除列表元素
- 读取文件的最后一行并输入到链接列表时出错
- 复制列表初始化的隐式转换的等级是多少
- LNK2038、MSVS2017 MAGMA的原因列表
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 没有为自己的结构调用列表推回方法
- 使用简单类型列表实现的指数编译时间.为什么
- 一对向量构造函数:初始值设定项列表与显式构造
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 通过for循环使用用户输入填充列表
- C++:如何使函数只返回作为列表一部分的字符串
- 概念中的cv限定符需要表达式参数列表
- 下面是我为检测链接列表中的循环而制作的代码
- 建议在运行时将带有类实例的列表从c++导入qml
- 如何维护资源管理器项目视图中当前可见的项目列表
- 在卡萨布兰卡形成编码参数的列表
- 生成列表的电源集