3

我必须写一个背包问题的蛮力实现。这是伪代码:

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 函数生成这个列表的幂集。是否有一种算法可以生成列表的子集?列表是正确的容器吗?

4

3 回答 3

2

不要为此使用列表,而是使用任何类型的随机访问数据结构,例如std::vector. 如果您现在有另一个std::vector<bool>,则可以将这两种结构一起使用来表示幂集的一个元素。即如果boolat 位置x为真,则该位置的元素在x子集中。

现在您必须遍历幂集中的所有集合。即您必须从每个当前子集生成下一个子集,以便生成所有集合。这只是在std::vector<bool>.

如果集合中的元素少于 64 个,则可以使用 long int 代替计数并在每次迭代时获取二进制表示。

于 2012-02-12T21:40:02.190 回答
2

这是一对可以解决问题的函数:

// 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提到的关系。正如李考所说,向量似乎是自然的方式。当然,不要在大套装上尝试这个!

于 2012-02-12T21:53:15.620 回答
1

数集 S = {0, 1, 2, ..., 2 n - 1} 形成位集 {1, 2, 4, ..., 2 n - 1 }的幂集。对于集合 S 中的每个数字,通过将数字的每一位映射到集合中的一个元素来导出原始集合的子集。由于遍历所有 64 位整数是难以处理的,因此您应该能够在不求助于 bigint 库的情况下做到这一点。

于 2012-02-12T21:39:20.277 回答