您的位置:首页 > 其它

背包问题的haskell解法

2011-04-24 08:28 288 查看
-- file: knapsack1.hs

maxVal [] [] _ = 0

maxVal (w:ws) (v:vs) aW =
if w > aW
then
without_it
else
max without_it (with_it+v)
where
without_it = maxVal ws vs aW
with_it = maxVal ws vs (aW-w)

weights = [1, 5, 3, 4]
vals = [15, 10, 9, 5]

evalue = maxVal weights vals 8

-- file: knapsack2.hs

maxVal [] [] _ = (0, 0)

maxVal (w:ws) (v:vs) aW =
if w > aW
then
(without_it, nc1+1)
else
(max without_it (with_it+v), nc1+nc2+1)
where
(without_it, nc1) = maxVal ws vs aW
(with_it, nc2) = maxVal ws vs (aW-w)

weights = [1, 5, 3, 4]
vals = [15, 10, 9, 5]

evalue = maxVal weights vals 8

-- file: knapsack3.hs

maxVal [] [] _ = (0, 0, [])

maxVal (w:ws) (v:vs) aW =
if w > aW then
(without_it, nc1+1, 0:xs1)
else if without_it > with_it then
(without_it, nc1+nc2+1, 0:xs1)
else
(with_it, nc1+nc2+1, 1:xs2)
where
(without_it, nc1, xs1) = maxVal ws vs aW
(with_it', nc2, xs2) = maxVal ws vs (aW-w)
with_it = with_it' + v

weights = [1, 5, 3, 4]
vals = [15, 10, 9, 5]

evalue = maxVal weights vals 8
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: