阅读《算法的乐趣》第3章的贪婪算法部分时,看到书上利用贪婪算法解决背包问题:
假设我们有n件物品,分别编号为1, 2...n。其中编号为i的物品价值为vi,它的重量为wi。为了简化问题,假定价值和重量都是整数值。现在,假设我们有一个背包,它能够承载的重量是W。现在,我们希望往包里装这些物品,使得包里装的物品价值最大化,那么我们该如何来选择装的东西呢?
书上写了几个重要的结构体和处理函数,这里我把程序补充完整,并且运行成功了。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef int SELECT_POLICY;
typedef struct tagObject{
int weight = 0;
int price = 0;
int status = 0;
}OBJECT;
typedef struct tagKnapSackProblem{
vector<OBJECT> objs;
int totalC;
}KNAPSACK_PROBLEM;
void PrintResult(vector<OBJECT>& objs){
for (int i = 0; i < static_cast<int>(objs.size()); i++)
{
if (objs[i].status == 1){
cout << (i+1) << " ";
}
}
cout << endl;
}
void GreedyAlgo(KNAPSACK_PROBLEM *problem, SELECT_POLICY spFunc(vector<OBJECT>&, int)){
int idx;
int ntc = 0;
while ((idx = spFunc(problem->objs, problem->totalC - ntc)) != -1){
if ((ntc + problem->objs[idx].weight) <= problem->totalC){
problem->objs[idx].status = 1;
ntc += problem->objs[idx].weight;
}
else{
problem->objs[idx].status = 2;
}
}
PrintResult(problem->objs);
}
//根据价值选取的贪婪算法
int Choosefunc1(vector<OBJECT>& objs, int c){
int index = -1;
int mp = 0;
for (int i = 0; i<static_cast<int>(objs.size()); i++){
if ((objs[i].status == 0) && (objs[i].price>mp)){
mp = objs[i].price;
index = i;
}
}
return index;
}
//根据重量选取的贪婪算法
int Choosefunc2(vector<OBJECT>& objs, int c){
int index = -1;
int mp = INT_MAX;
for (int i = 0; i < static_cast<int>(objs.size()) ; i++)
{
if ((objs[i].status==0)&&(objs[i].weight<mp))
{
mp = objs[i].weight;
index = i;
}
}
return index;
}
//根据价值密度选取的贪婪算法
int Choosefunc3(vector<OBJECT>& objs, int c){
int index = -1;
int mp = 0;
for (int i = 0; i < static_cast<int>(objs.size()); i++)
{
double pricePerWeight = 1.0 *objs[i].price / objs[i].weight;
if ((objs[i].status == 0) && (pricePerWeight > mp))
{
mp = pricePerWeight;
index = i;
}
}
return index;
}
int main(){
OBJECT initObject;
KNAPSACK_PROBLEM problem = { { initObject, initObject, initObject, initObject, initObject, initObject, initObject }, 150 };
KNAPSACK_PROBLEM *problemNow = &problem;
for (int i = 0; i < 7; i++)
{
cin >> problemNow->objs[i].weight >> problemNow->objs[i].price >> problemNow->objs[i].status;
cout << problemNow->objs[i].weight << " " << problemNow->objs[i].price << " " << problemNow->objs[i].status << endl;
}
GreedyAlgo(problemNow, Choosefunc3);
return 0;
}
当然,书上也提了,0-1背包问题的正确最优结果应该用动态规划来求得,我还需要进一步看书学习。