【问题标题】:Generating the power set of a list生成列表的幂集
【发布时间】:2012-03-04 09:24:36
【问题描述】:

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

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 函数生成这个列表的幂集。是否有一种算法可以生成列表的子集?列表是否适合使用?

【问题讨论】:

    标签: c++ brute-force knapsack-problem powerset


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!这很有帮助,老实说,我花了过去 4 个小时的大部分时间来理解子集的二进制表示。
    【解决方案2】:

    不要为此使用列表,而是使用任何类型的随机访问数据结构,例如std::vector。如果您现在有另一个std::vector&lt;bool&gt;,您可以同时使用这两个结构来表示幂集的一个元素。 IE。如果x 位置的bool 为真,则x 位置的元素在子集中。

    现在您必须遍历幂集中的所有集合。 IE。您必须从每个当前子集生成下一个子集,以便生成所有集合。这只是在std::vector&lt;bool&gt; 上以二进制计数。

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2014-01-22
        • 2021-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多