1 普通背包问题

有 n 个物品和一个大小为 m 的背包. 给定数组 A 表示每个物品的大小和数组 V 表示每个物品的价值.

问最多能装入背包的总价值是多大?

class Solution:
    """
    @param m: An integer m denotes the size of a backpack
    @param A: Given n items with size A[i]
    @param V: Given n items with value V[i]
    @return: The maximum value
    """
    def backPackII(self, m, A, V):
        # write your code here
        n = len(A)
        dp = [0 for _ in range(m+1)]
        
        for i in range(n):
            for j in range(len(dp)-1, A[i]-1, -1):
                dp[j] = max(dp[j], dp[j-A[i]] + V[i])
        
        return dp[-1]

基础的背包问题,最重要的就是递推式:在这个二维dp数组(可优化为1维)中,每行代表前n个的最佳组合,在空间为m时的最大价值。选或者不选,都考虑,即可枚举出所有情况。
dp的难点也在于这种大胆的假设,假设前n个最佳组合,是一个大胆的选择。
最神奇的点在于,你不需要显式的记录哪个装了哪个没装,以及已经装了哪几个元素等信息。
细节可见下面的dp表。
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用贪心算法解决普通背包问题的C++代码: ```cpp #include <iostream> #include <algorithm> using namespace std; struct goods { int weight; int value; double ratio; }; bool cmp(goods a, goods b) { return a.ratio > b.ratio; } double knapsack(goods* items, int n, int capacity) { sort(items, items + n, cmp); int current_weight = 0; double current_value = 0.0; for (int i = 0; i < n; ++i) { if (current_weight + items[i].weight <= capacity) { current_weight += items[i].weight; current_value += items[i].value; } else { int remaining_capacity = capacity - current_weight; current_value += items[i].ratio * remaining_capacity; break; } } return current_value; } int main() { int n, capacity; cout << "请输入物品数量和背包容量:" << endl; cin >> n >> capacity; goods* items = new goods[n]; cout << "请输入每个物品的重量和价值:" << endl; for (int i = 0; i < n; ++i) { cin >> items[i].weight >> items[i].value; items[i].ratio = (double)items[i].value / items[i].weight; } double result = knapsack(items, n, capacity); cout << "可以装进背包的最大价值为:" << result << endl; delete[] items; return 0; } ``` 在此代码中,我们定义了一个结构体 `goods` 来表示物品,其中包括重量、价值和价值与重量比值三个成员变量。在 `cmp` 函数中,我们按照价值与重量比值从大到小排序。在 `knapsack` 函数中,我们首先对物品数组按照价值与重量比值从大到小排序,然后从大到小依次将物品放入背包中,直到背包装满为止。如果当前物品不能完全放入背包中,则将其部分放入背包中,并相应地计算价值。最后返回背包中的总价值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值