固定数量的背包0-1

时间:2014-10-19 00:09:45

标签: algorithm dynamic-programming knapsack-problem

我正在编写带有多个约束的背包0-1的变体。除了重量限制,我还有一个数量约束,但在这种情况下,我想解决背包问题,因为我需要在我的背包中有正好n项,重量小于或等于W我目前正在为基于http://rosettacode.org/wiki/Knapsack_problem/0-1#Ruby的Rosetta Code代码的简单0-1案例实现动态编程ruby解决方案。

实施固定数量约束的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

您可以在表格中添加第三个维度:项目数量。包含的每个项目都会在权重维度中添加权重,并在计数维度中计算。

def dynamic_programming_knapsack(problem)
  num_items = problem.items.size
  items = problem.items
  max_cost = problem.max_cost
  count = problem.count
  cost_matrix = zeros(num_items, max_cost+1, count+1)

  num_items.times do |i|
    (max_cost + 1).times do |j|
      (count + 1).times do |k|
        if (items[i].cost > j) or (1 > k)
          cost_matrix[i][j][k] = cost_matrix[i-1][j][k]
        else
          cost_matrix[i][j][k] = [
              cost_matrix[i-1][j][k],
              items[i].value + cost_matrix[i-1][j-items[i].cost][k-1]
            ].max
        end
      end
    end
  end
  cost_matrix
end

要查找解决方案(要选择的项目),您需要查看网格cost_matrix[num_items-1][j][k],查看jk的所有值,并找到具有最大值的单元格

找到获胜单元后,您需要向后追溯到开始(i = j = k = 0)。在您检查的每个单元格上,您需要确定是否使用了项i来到达此处。

def get_used_items(problem, cost_matrix)
  itemIndex = problem.items.size - 1
  currentCost = -1
  currentCount = -1
  marked = Array.new(cost_matrix.size, 0) 

  # Locate the cell with the maximum value
  bestValue = -1
  (problem.max_cost + 1).times do |j|
    (problem.count + 1).times do |k|
      value = cost_matrix[itemIndex][j][k]
      if (bestValue == -1) or (value > bestValue)
        currentCost = j
        currentCount = k
        bestValue = value
      end
    end
  end

  # Trace path back to the start
  while(itemIndex >= 0 && currentCost >= 0 && currentCount >= 0)
    if (itemIndex == 0 && cost_matrix[itemIndex][currentCost][currentCount] > 0) or
        (cost_matrix[itemIndex][currentCost][currentCount] != cost_matrix[itemIndex-1][currentCost][currentCount])
      marked[itemIndex] = 1
      currentCost -= problem.items[itemIndex].cost
      currentCount -= 1
    end
    itemIndex -= 1
  end
  marked
end