zoukankan      html  css  js  c++  java
  • 0-1背包问题算法详解及实现

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

  • 相关阅读:
    攻城狮在路上(肆)How tomcat works(一) 简单的web服务器
    攻城狮在路上(肆)How tomcat works(零) 前言说明
    font-face使用备忘
    subversion安装使用
    判断一个类到底是从哪个jar包中调用的工具类
    JavaScript实例
    Nginx(一)
    PHP面向对象(七)
    PHP面向对象(六)
    PHP面向对象(五)
  • 原文地址:https://www.cnblogs.com/xiaotan-code/p/6670630.html
Copyright © 2011-2022 走看看