算法学习--部分背包问题(贪心)

问题描述

有一个背包,背包容量是 M =150,有 7 个物品,物品可以分割成任意大小,要求尽可能让装入背包中的物品总价值最大,但不能超过总容量

在这里插入图片描述

思路:按照物品性价比排序,性价比高的尽量多拿

#include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

//物品类
class Thing {
public:
	double weight;//重量
	double value;//总价值
	double price;//单价
	Thing(double w, double v) :weight(w), value(v) {
		price = value / weight;
	}
};

bool cmp(const Thing& t_1, const Thing& t_2) {
	return t_1.price > t_2.price;
}

int main() {
	double bagSize = 150;//背包容量
	double maxValue = 0;//最大价值
	vector<double> v_weight = { 35, 30, 60, 50, 40, 10 };
	vector<double> v_value = { 10, 40, 30, 50, 35, 40 };
	vector<Thing> v_thing;
	for (int i = 0; i < v_weight.size(); i++) {
		Thing thing(v_weight[i], v_value[i]);
		v_thing.push_back(thing);
	}
	sort(v_thing.begin(), v_thing.end(), cmp);
	for (Thing t : v_thing) {
		if (t.weight <= bagSize) {//全选
			maxValue += t.value;
			bagSize -= t.weight;
		}
		else {
			maxValue += bagSize * t.price;
			break;
		}
	}
	cout << fixed << setprecision(2) << maxValue << endl;
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值