xiaotan-code

#-*- coding:utf-8 -*-

import numpy as np

def package1(w,v,c,n):#求取m和choose函数

    m=np.zeros((n+1,c+1),dtype=int)

    choose=np.zeros((n+1,c+1),dtype=bool)

    for j in range(c,0,-1):

        if j>=w[n-1]:

            m[n,j]=v[n-1]

            choose[n, j] = 1

        else:

            m[n, j]=0

            choose[n, j] = 0

    for i in range(n-1,0,-1):

        for j in range(c,0,-1):

            if j<w[i-1]:

                m[i,j]=m[i+1,j]

                choose[i,j]=0

            else:

                if m[i+1,j]>m[i+1,j-w[i-1]]+v[i-1]:

                    m[i, j]=m[i+1,j]

                    choose[i, j] = 0

                else:

                    m[i, j]=m[i+1,j-w[i-1]]+v[i-1]

                    choose[i, j] = 1

    return m,choose

def output(m, choose,c,n):#构造最优解函数

    result = []

    j = c

    for i in range(1,n+1):

        result.append(choose[i, j])

        j = j - w[i - 1] * choose[i, j]

        i = i + 1

    print \'max value:\',m[1, c]

    print \'choose result:\',result

if __name__==\'__main__\':

    w=[4,3,2]

    v=[5,2,1]

    m, choose=package1(w,v,6,3)

    output(m, choose, 6, 3)

运行结果:

max value: 6

choose result: [True, False, True]

 

希望以上讲解能够帮到大家,下一篇会是对此算法进行一个优化,有兴趣的可以一起学习。

 

 

 

 由于博客园不好编辑公式,因此写好了截图的,以上为原创,欢迎大家指正

where there is a will,there is a way where there is a will,there is a way

where there is a will,there is a way where there is a will,there is a way

where there is a will,there is a way where there is a will,there is a way

where there is a will,there is a way where there is a will,there is a way

where there is a will,there is a way where there is a will,there is a way

where there is a will,there is a way where there is a will,there is a way

where there is a will,there is a way where there is a will,there is a way

 

分类:

技术点:

相关文章:

  • 2021-09-29
  • 2021-09-29
  • 2021-09-29
  • 2021-09-29
  • 2021-09-29
  • 2021-09-29
  • 2021-11-16
  • 2021-09-29
猜你喜欢
  • 2021-08-13
  • 2021-10-09
  • 2021-09-29
  • 2021-09-26
  • 2021-11-16
  • 2020-02-17
  • 2021-07-02
相关资源
相似解决方案