揹包問題的haskell解法

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章