GLPK/背包问题
外观
< GLPK
背包问题可以定义如下:给定一组大小为 的物品 和利润 ,选择一个子集,这些子集适合容量 并且最大化所选物品的总利润。
| 最大化 | |
| 受制于 |
背包问题属于 NP-hard 问题类 [1]。
解决背包问题的一种常用方法是通过 动态规划 (DP)。下面的示例展示了如何将背包问题公式化为在 GMPL (MathProg) 中实现的混合整数规划 (MIP)。
# en.wikipedia.org offers the following definition:
# The knapsack problem or rucksack problem is a problem in combinatorial optimization:
# Given a set of items, each with a weight and a value, determine the number of each
# item to include in a collection so that the total weight is less than a given limit
# and the total value is as large as possible.
#
# This file shows how to model a knapsack problem in GMPL.
# Size of knapsack
param c;
# Items: index, size, profit
set I, dimen 3;
# Indices
set J := setof{(i,s,p) in I} i;
# Assignment
var a{J}, binary;
maximize obj :
sum{(i,s,p) in I} p*a[i];
s.t. size :
sum{(i,s,p) in I} s*a[i] <= c;
solve;
printf "The knapsack contains:\n";
printf {(i,s,p) in I: a[i] == 1} " %i", i;
printf "\n";
data;
# Size of the knapsack
param c := 100;
# Items: index, size, profit
set I :=
1 10 10
2 10 10
3 15 15
4 20 20
5 20 20
6 24 24
7 24 24
8 50 50;
end;
现在使用 GLPSOL 保存并运行此模型(在 Intel Core i5 处理器上花费 1 秒)。
$ glpsol --math knapsack.mod
得到
The knapsack contains: 2 4 5 8
- ↑ Kellerer, Hans; Pferschy, Ulrich; Pferschy, David (2004). Knapsack Problems. Springer-Verlag. ISBN 3-540-40286-1.