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

  • 相关阅读:
    一步步用新浪SAE免费教大家搭建个人博客(wordpress 3.0.4 for SAE )
    欢迎大家来访西北狼网络乌托邦
    教大家如何让新浪SAE上安装wordpress实现伪静态
    CSDN 600万用户数据信息泄露并道歉
    推荐5款好用的屏幕录像软件
    IPv6无法解决全部安全问题
    详解STP以及工作过程
    如何在WordPress中实现彩色标签云
    EIGRP和RIP的一个综合性很强的实验(变态实验之一)
    查看系统等待的sql
  • 原文地址:https://www.cnblogs.com/xiaotan-code/p/6670630.html
Copyright © 2011-2022 走看看