给定背包容量50Kg,物品信息
物品1,重量10Kg,价值60元
物品2,重量20Kg,价值100元
物品3,重量30Kg,价值120元
注意:可以部分装入
图片和题目转自https://blog.csdn.net/songshimvp1/article/details/52350542
#pragma once
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<stack>
using namespace std;
const int MAXSIZE = 3;
class BAGS
{
public:
BAGS(){}
BAGS(int i) {
if (i == 1) {
init();
}
}
~BAGS(){}
void init() {
m_weight[0] = 20;
m_value[0] = 100;
m_VEachW[0] = 5;
m_weight[1] = 30;
m_value[1] = 120;
m_VEachW[1] = 4;
m_weight[2] = 10;
m_value[2] = 60;
m_VEachW[2] = 6;
m_bagCapcity = 50;
}
void getMaxValue() {
vector<int> pos;
for (int i = 0; i < MAXSIZE; i++) {
pos.push_back(i);
}
sortPosByVeachW(pos);
//for(int i:pos) cout << m_VEachW[i] << endl;
int maxValue = encloseByPos(pos);
cout << maxValue << endl;
}
void sortPosByVeachW(vector<int>& pos) {
for (int i = 0; i < MAXSIZE; i++) {
bool hasUpdate = false;
for (int j = 0; j+1 < MAXSIZE; j++) {
int pos1 = pos[j], pos2 = pos[j + 1];//important!!
if (m_VEachW[pos1] < m_VEachW[pos2]) {
swap(pos[j], pos[j+1]);
hasUpdate = true;
}
}
if (!hasUpdate) break;
}
}
int encloseByPos(vector<int> &pos) {
int maxValue = 0;
int i = 0;
int curPos = pos.at(i);
int residualCapcity = m_bagCapcity;
while (residualCapcity != 0) {
if (residualCapcity >= m_weight[curPos]) {
maxValue += m_value[curPos];
residualCapcity -= m_weight[curPos];
i++;
if(i<MAXSIZE)
curPos = pos[i];
}
else {
maxValue += residualCapcity * m_VEachW[curPos];
break;
}
}
return maxValue;
}
private:
int m_weight[MAXSIZE], m_value[MAXSIZE],m_VEachW[MAXSIZE];
int m_bagCapcity;
};
void testForBag() {
BAGS test(1);
test.getMaxValue();
}
要注意的:
1,按 元/kg 做关联排序,即只对位置排序,小心交换的位置不是直接下标,而是pos数组中的数据
for (int j = 0; j+1 < MAXSIZE; j++) {
int pos1 = pos[j], pos2 = pos[j + 1];//important!!
if (m_VEachW[pos1] < m_VEachW[pos2]) {
swap(pos[j], pos[j+1]);
hasUpdate = true;
}
2,函数的返回值尽量为空,大可以把返回值作为引用,如下
void sortPosByVeachW(vector<int>& pos);//推荐使用一个输入,返回void
vector<int>& sortPosByVeachW();
3,out_of_range:
i++;
if(i<MAXSIZE) curPos = pos[i];
4,贪心法:每次装入的都是单位价值最高的