您的位置:首页 > 编程语言 > C语言/C++

01背包问题与分数背包问题 C++实现

2016-11-12 23:15 555 查看

01背包问题与分数背包问题 C++实现

贪心对动态规划

两个背包问题都具有最优子结构性质。对01背包问题,考虑重量不超过W而价值最高的了包装方案。如果我们将商品j从此方案中删除,则剩余商品必须是重量不超过W−ωj的价值最高档案。

虽然两个问题类似,但我们用贪心策略可以求解分数背包问题,而不能求解01背包问题(需要用动态规划方法求解),我们首先计算每个商品的每磅价值vi/ωi。遵循贪心策略,小偷尽量多地拿走每磅价值最高的商品。如果商品已被全部拿走而背包尚未满,他继续尽量多地拿走每磅价值第二高的商品,以此类推,直到重量达到上限W。因此,通过将商品按照每磅价值排序,贪心算法的运行时间为O(nlgn)。

源代码

01背包:

#include <iostream>
#include <utility>
#include <vector>
#include <algorithm>

using namespace std;

//Data.
vector<int> temp_VecP = { 0,17,2,3,4,5,6 }, temp_VecW = { 0,6,5,4,3,2,1 };

//Knapsack_Problem_01 by DP.
pair<vector<int>, vector<vector<int>>> Knapsack_Problem_01(vector<int> const &temp_VecP, vector<int> const &temp_VecW, int const &temp_w) {
vector<int> temp_VecS;
vector<vector<int>> temp_VecR;
temp_VecS.resize(temp_VecP.size());
temp_VecR.resize(temp_VecP.size());

for(auto &i : temp_VecR) {
i.resize(temp_w + 1);
}

//Solving the max price.
for(auto i = 1; i != temp_VecP.size(); ++i) {
for(auto j = 1; j <= temp_w; ++ j) {
if(j < temp_VecW[i]) {
temp_VecR[i][j] = temp_VecR[i - 1][j];
}
else {
temp_VecR[i][j] = max(temp_VecR[i - 1][j - temp_VecW[i]] + temp_VecP[i], temp_VecR[i - 1][j]);
}
}
}

//Saving the result of each one.
auto w = temp_w;
for(auto i = temp_VecP.size() - 1; i >= 1; --i) {
if(temp_VecR[i][w] > temp_VecR[i - 1][w]) {
temp_VecS[i] = 1;
w -= temp_VecW[i];
}
else {
temp_VecS[i] = 0;
}
}

return make_pair(temp_VecS, temp_VecR);
}

int main() {
auto temp_Pair =  Knapsack_Problem_01(temp_VecP, temp_VecW, 10);

for (auto &i : temp_Pair.first) {
cout << i << " ";
}
cout << endl << endl;

for(auto &i : temp_Pair.second) {
for(auto &j : i) {
cout << j << " ";
}
cout << endl;
}

return 0;
}


分数背包:

#include <iostream>
#include <utility>
#include <vector>

using namespace std;

//Data.
vector<int> temp_VecP = { 0,60,100,120 }, temp_VecW = { 0,10,20,30 };

//Knapsack_Problem_fraction by Greedy.
pair<vector<pair<int, int>>, int> Knapsack_Problem_fraction(vector<int> const &temp_VecP, vector<int> const &temp_VecW, int const &temp_w) {
vector<pair<int, int>> temp_VecPair;
auto temp_v = 0, temp_c = 0;

for(auto i = 1; i != temp_VecP.size(); ++i) {
if(temp_VecW[i] + temp_c >= temp_w) {
temp_VecPair.push_back(make_pair(temp_VecP[i], temp_w - temp_c));
temp_v += (temp_w - temp_c) * (temp_VecP[i] / temp_VecW[i]);
return make_pair(temp_VecPair, temp_v);
}
temp_VecPair.push_back(make_pair(temp_VecP[i], temp_VecW[i]));
temp_v += temp_VecP[i];
temp_c += temp_VecW[i];
}

return make_pair(temp_VecPair, temp_v);
}

int main() {
auto temp_VecPair = Knapsack_Problem_fraction(temp_VecP, temp_VecW, 50);
cout << temp_VecPair.second << endl;

for(auto &i : temp_VecPair.first) {
cout << i.first << " " << i.second << endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: