动态规划问题

Dynamic Programming Problem

本文关键字:问题 动态规划      更新时间:2023-10-16

好吧,我真的不需要代码本身的帮助,但理解我到底要做什么,以便编写代码。简而言之,我有1000个项目,每个项目都有一组资源,我有一个(一定数量的)资源来计算我能选择的最佳项目。

最佳利润函数的伪代码如下:

bestProfit:

Parameters - 
            projects: a vector of projects
            r:        the resources available to solve the subinstance 
            valueMap: the map data structure that is used for memoization
            n:        only projects numbered 0,...,n-1 may be 
                      used to solve the subinstance
Returns -   the maximum amount of profit that may be obtained on this
           subinstance of the optimization problem
Post-condition – If n > 0, then valueMap contains an entry 
                whose key is (r, n).

If n equals 0
     return 0
Check valueMap to see whether this subinstance has already been solved
-   If so, then return the previously computed result (function terminates)
best1 = bestProfit(projects, r, valueMap, n-1)
Check whether r provides enough resources to undertake project n-1
-   If so, then best2 = bestProfit(projects, r – projects[n-1].requirements, valueMap, n-1) 
+ projects[n-1].profit
 Else
     best2 = 0
If best1 >= best2
   Store (r, n) -> (best1, false) in valueMap
   Return best1
Else
   Store (r, n) -> (best2, true) in valueMap
   Return best2

当我递归调用bestProfit时,best1应该检查子问题是否已经解决。考虑到可行性检查只基于最后一个项目。换句话说,它看起来像一棵平衡的树。我无法理解的是如何在递归期间在映射上插入值?基本上,最后的if/else语句在遍历整个项目集之前不会发生。只有最后的值会被插入到映射中。我只是想要一些关于如何正确地写递归的指针。

就像我之前说过的,我不是在寻找代码,而是一种理解这个伪代码对我的项目在c++中的要求的方法。正是这种逻辑在这一点上让我发疯,因为我不能把它放在一起工作。感谢大家的关注,并尽可能提供更好的见解。

我将返回一个数据结构,它既表示利润,也表示获得利润的解决方案。将确切的数据结构存储在valueMap中。这将使您的代码更直接。

基本上,"写出正确的递归解。添加记忆,使它更快。"

你不使用自下而上的解决方案吗?

这是一个直接应用的背包问题与许多启发式适用于使它成为贪婪的解决方案,如果分数是可能的…

对于你的问题,递归式是让W->定义你的资源是否足够
问题"k"设N ->一个以0为索引的问题集设V -> 0为解决每个问题的潜在利润指标OPT[i][j] = MAX(OPT[i-1][j], OPT[i-1][j- w [i]]+V[i]),其中'i'是到问题列表。J是表示可用资源数量的索引。你的解决方案是OPT[size[N]][W]解释:直观地说,子问题是用可用资源j从i中选择最优项目集…

递归是不好的不允许许多编译器优化可能与正常的函数调用。