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

问题描述

有一个背包,背包容量是 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;
}
发布了25 篇原创文章 · 获赞 17 · 访问量 714

猜你喜欢

转载自blog.csdn.net/mu_mu_mu_mu_mu/article/details/104665406