01背包问题代码

/
//       question 2        //
/
//一个小偷夜晚潜入去博物馆里面偷画
//博物馆共有N幅画, 每幅画的重量为w_i, 每幅画的价格为v_i
//但是小偷的包只能装下最多C的重量, 请问小偷最多能收获多少钱
#include <iostream>
#include <vector>
#include <stdio.h>

using namespace std;
 
// helper function
int max(int a, int b) { return (a > b) ? a : b; }
 
// c: capacity of theft's bag
// W: array of weight of each art
// V: array of value of each art
int MuseumTheft(int c, int W[], int V[])
{   
	vector<int> ans(c+1, 0);
	for(int i = 0; i<3; i++){
		for(int j = c; j>=1; j--){
			//如果想要减小空间复杂度就需要逆向遍历重量,因为前序遍历会造成前面的值更改而影响后面更新的值
			if(j>=W[i]){
				ans[j] = max(ans[j], ans[j-W[i]]+V[i]);
			}
		}
	}
	int max_value = ans.back();
    return max_value;

}
 
int main()
{
    int V[] = { 60, 100, 120 };
    int W[] = { 10, 40, 50 };
    int c = 50;
    cout << MuseumTheft(c, W, V);
    return 0;
}

背包问题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值