这个怎么样?
给定 Haskell 中针对 0-1 背包问题的标准动态解决方案,可在此处找到,
inv = [("map",9,150), ("compass",13,35), ("water",153,200), ("sandwich",50,160),
("glucose",15,60), ("tin",68,45), ("banana",27,60), ("apple",39,40),
("cheese",23,30), ("beer",52,10), ("cream",11,70), ("camera",32,30),
("tshirt",24,15), ("trousers",48,10), ("umbrella",73,40),
("trousers",42,70), ("overclothes",43,75), ("notecase",22,80),
("sunglasses",7,20), ("towel",18,12), ("socks",4,50), ("book",30,10)]
knapsack = foldr addItem (repeat (0,[])) where
addItem (name,w,v) list = left ++ zipWith max right newlist where
newlist = map (\(val, names)->(val + v, name:names)) list
(left,right) = splitAt w list
main = print $ (knapsack inv) !! 400
我们添加了一个填充机制,将库存排列顺序放置在下一个有空间的背包中,
stuff (name,w,v) left (v2,[]) = (v2,left)
stuff (name,w,v) left (v2,(cap, lst):xs) =
if w <= cap
then (v + v2, left ++ [(cap - w, (name,w,v):lst)] ++ xs)
else stuff (name,w,v) (left ++ [(cap,lst)]) (v2,xs)
并将其替换为映射函数。把它们放在一起:
inv = [("map",9,150), ("compass",13,35), ("water",153,200), ("sandwich",50,160),
("glucose",15,60), ("tin",68,45), ("banana",27,60), ("apple",39,40),
("cheese",23,30), ("beer",52,10), ("cream",11,70), ("camera",32,30),
("tshirt",24,15), ("trousers",48,10), ("umbrella",73,40),
("trousers",42,70), ("overclothes",43,75), ("notecase",22,80),
("sunglasses",7,20), ("towel",18,12), ("socks",4,50), ("book",30,10)]
capacity = 200::Int
numKnapsacks = 3
stuff (name,w,v) left (v2,[]) = (v2,left)
stuff (name,w,v) left (v2,(cap, lst):xs) =
if w <= cap
then (v + v2, left ++ [(cap - w, (name,w,v):lst)] ++ xs)
else stuff (name,w,v) (left ++ [(cap,lst)]) (v2,xs)
knapsack = foldr addItem (repeat (0, replicate numKnapsacks (capacity,[])))
where addItem (name,w,v) list = left ++ zipWith max right newlist
where newlist = map (stuff (name,w,v) []) list
(left,right) = splitAt w list
main = print $ (knapsack inv) !! 600
输出(每个背包的剩余重量容量和内容后的总值):
*Main> main
(1062,[(1,[("map",9,150),("tshirt",24,15),("trousers",42,70),
("overclothes",43,75),("notecase",22,80),("sunglasses",7,20),
("towel",18,12),("socks",4,50),("book",30,10)]),
(0,[("compass",13,35),("cheese",23,30),("cream",11,70),
("camera",32,30),("trousers",48,10),("umbrella",73,40)]),
(1,[("sandwich",50,160),("glucose",15,60),("tin",68,45),("banana",27,60),
("apple",39,40)])])