有一个背包,背包容量是C,有N(1
要求尽可能让装入背中的物品总价值最大,但不能超过总容量。其中物品可以分割成任意大小。
| 小数背包问题 | 0 1背包问题 |
|---|---|
| 物品可拆分 | 物品是个不可分的整体 |
| 背包一定被装满 | 背包可能有空余 |
| 贪心算法 | DP算法 |
- #include
- #include
- using namespace std;
-
-
- class item {
- public:
- int val=0;
- int weight=0;
- double rate=0;
- friend bool operator<(const item& it1, const item& it2);
- };
- bool operator<(const item& it1, const item& it2) {
- return it1.rate > it2.rate;
- }
-
- bool compare(const item& it1, const item& it2)
- {
- return it1 < it2;
- }
-
- void sol()
- {
- item a[3] = { {6,30},{2,20},{5,10} };
- double res = 0;
-
- int c = 20;//背包总容量
- int left = c;//剩余容量
- //求物品的价值率
- for (int i = 0; i < 3; i++)
- {
- a[i].rate = static_cast<double>(a[i].val) / a[i].weight;
- cout << "val:" << a[i].val << " weight:" << a[i].weight << " rate:" << a[i].rate << endl;
- }
- //按照价值率对物品进行从大到小排序
- sort(a, a + 3, compare);
- //每次都选择价值率较大者装入背包
- for (int i = 0; i < 3; i++)
- {
- //如果当前物品能够被装入背包
- if (a[i].weight <= left)
- {
- res += a[i].val;
- left = c - a[i].weight;
- }
- else {//如果当前物品不能装入背包
- res += a[i].rate * left;
- }
- }
- cout << res << endl;
- }
-
- int main() {
- sol();
- return 0;
- }
参考: