背包问题的haskell解法

来源:互联网 发布:java 爬虫 编辑:程序博客网 时间:2024/06/10 07:25

-- 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

原创粉丝点击