码迷,mamicode.com
首页 > 编程语言 > 详细

贪心算法解决背包问题?

时间:2020-12-09 12:29:02      阅读:16      评论:0      收藏:0      [点我收藏+]

标签:aci   cti   var   push   UNC   cap   bsp   for   greedy   

var items = [‘A‘,‘B‘,‘C‘,‘D‘]
var values = [50,220,60,60]
var weights = [5,20,10,12]
var capacity = 32 //背包容积

greedy(values, weights, capacity) // 320

function greedy(values, weights, capacity) {
        var result = 0
        var rest = capacity
        var sortArray = []
        var num = 0
        values.forEach((v, i) => {
          sortArray.push({
            value: v,
            weight: weights[i],
            ratio: v / weights[i]
          })
        })
        sortArray.sort((a, b) => b.ratio - a.ratio)
        sortArray.forEach((v, i) => {
          num = parseInt(rest / v.weight)
          rest -= num * v.weight
          result += num * v.value
        })
        return result
      }

贪心算法解决背包问题?

标签:aci   cti   var   push   UNC   cap   bsp   for   greedy   

原文地址:https://www.cnblogs.com/programb/p/14068872.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!