背包问题经典

如何解决背包问题经典

| 因此,我必须在上课时解决背包问题。到目前为止,我已经提出了以下建议。我的比较器是确定两个主题中哪个主题更好的函数(通过查看相应的(值,工作)元组)。 我决定对工作量小于maxWork的可能主题进行迭代,为了找出在任何给定回合中哪个主题是最佳选择,我将最近的主题与我们尚未使用的所有其他主题进行了比较。
def greedyAdvisor(subjects,maxWork,comparator):
    \"\"\"
    Returns a dictionary mapping subject name to (value,work) which includes
    subjects selected by the algorithm,such that the total work of subjects in
    the dictionary is not greater than maxWork.  The subjects are chosen using
    a greedy algorithm.  The subjects dictionary should not be mutated.

    subjects: dictionary mapping subject name to (value,work)
    maxWork: int >= 0
    comparator: function taking two tuples and returning a bool
    returns: dictionary mapping subject name to (value,work)
    \"\"\"

    optimal = {}
    while maxWork > 0:
        new_subjects = dict((k,v) for k,v in subjects.items() if v[1] < maxWork)
        key_list = new_subjects.keys()
        for name in new_subjects:
            #create a truncated dictionary
            new_subjects = dict((name,new_subjects.get(name)) for name in key_list)
            key_list.remove(name)
            #compare over the entire dictionary
            if reduce(comparator,new_subjects.values())==True:
                #insert this name into the optimal dictionary
                optimal[name] = new_subjects[name]
                #update maxWork
                maxWork = maxWork - subjects[name][1]
                #and restart the while loop with maxWork updated
                break
    return optimal  
问题是我不知道为什么这是错误的。我遇到了错误,而且我不知道我的代码在哪里出错(即使在抛出print语句之后)。帮助将不胜感激,谢谢!     

解决方法

与OPT相比,使用简单的贪心算法不会对解决方案的质量提供任何限制。 这是一个完整的多项式时间(1-epsilon)*背包的OPT近似伪代码:
items = [...]  # items
profit = {...} # this needs to be the profit for each item
sizes = {...}  # this needs to be the sizes of each item
epsilon = 0.1  # you can adjust this to be arbitrarily small
P = max(items) # maximum profit of the list of items
K = (epsilon * P) / float(len(items))
for item in items:
    profit[item] = math.floor(profit[item] / K)
return _most_prof_set(items,sizes,profit,P)
现在,我们需要定义最有利可图的集合算法。我们可以通过一些动态编程来做到这一点。但是首先让我们回顾一些定义。 如果P是集合中最赚钱的商品,而n是我们拥有的商品数量,那么nP显然是允许利润的微不足道的上限。对于{1,...,n}中的每个i和{1,...,nP}中的p,我们让Sip表示总利润恰好为p并且总大小最小的项的子集。然后,让A(i,p)表示集合Sip的大小(如果不存在,则为无穷大)。我们可以很容易地证明,{1,...,nP}中p的所有值都已知A(1,p)。我们将定义一个递归来计算A(i,p),并将其用作动态规划问题,以返回近似解。
A(i + 1,p) = min {A(i,p),size(item at i + 1 position) + A(i,p - profit(item at i + 1 position))} if profit(item at i + 1) < p otherwise A(i,p)
最后,我们给出_most_prof_set
def _most_prof_set(items,P):
    A = {...}
    for i in range(len(items) - 1):
        item = items[i+1]
        oitem = items[i]
        for p in [P * k for k in range(1,i+1)]:
            if profit[item] < p:
                A[(item,p)] = min([A[(oitem,p)],\\
                                     sizes[item] + A[(item,p - profit[item])]])
            else:
                A[(item,p)] = A[(oitem,p)] if (oitem,p) in A else sys.maxint
    return max(A) 
资源     ,
def swap(a,b):
    return b,a

def sort_in_decreasing_order_of_profit(ratio,weight,profit):
    for i in range(0,len(weight)):
        for j in range(i+1,len(weight)) :
            if(ratio[i]<ratio[j]):
                ratio[i],ratio[j]=swap(ratio[i],ratio[j])
                weight[i],weight[j]=swap(weight[i],weight[j])
                profit[i],profit[j]=swap(profit[i],profit[j])
    return ratio,profit          
def knapsack(m,i,newpr):

    if(i<len(weight) and m>0):
        if(m>weight[i]):
            newpr+=profit[i]
        else:
            newpr+=(m/weight[i])*profit[i]  
        newpr=knapsack(m-weight[i],i+1,newpr)
    return newpr
def printing_in_tabular_form(ratio,profit):

    print(\" WEIGHT\\tPROFIT\\t RATIO\")
    for i in range(0,len(ratio)):
        print (\'{}\\t{} \\t {}\'.format(weight[i],profit[i],ratio[i]))

weight=[10.0,10.0,18.0]
profit=[24.0,15.0,25.0]
ratio=[]
for i in range(0,len(weight)):
    ratio.append((profit[i])/weight[i])
#caling function
ratio,profit=sort_in_decreasing_order_of_profit(ratio,profit) 
printing_in_tabular_form(ratio,profit)

newpr=0
newpr=knapsack(20.0,newpr)          
print(\"Profit earned=\",newpr)
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res