## KusanoNEU的博客

No day but today.

# Knapsack problem I

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <Windows.h>

using namespace std;

// given n objects and a knapsack with capacity limit W
// object i weigts wi > 0 and has value vi > 0
// Goal: fill knapsack that max total value of objects

struct Item
{
int value;
int weight;
};

bool operator<(const Item &lhs, const Item &rhs)
{
return lhs.weight < rhs.weight;
}

// O(n*W) time complexity

int Knapsack(vector<Item> items, int W, vector<Item> &solution)
{
int n = static_cast<int>(items.size());
sort(items.begin(), items.end());
vector<vector<int>> M(n + 1, vector<int>(W + 1, 0));

for (int i = 1; i <= n; ++i)
{
for (int w = 0; w <= W; ++w)
{
if (items[i - 1].weight > w)
M[i][w] = M[i - 1][w];
else
M[i][w] = max(M[i - 1][w], items[i - 1].value + M[i - 1][w - items[i - 1].weight]);
}
}

int i = n, w = W;
while (i >= 0 && w > 0)
{
if (M[i][w] > M[i - 1][w])
{
solution.push_back(items[i - 1]);
w -= items[i - 1].weight;
}
--i;
}

return M[n].back();
}
int main()
{
vector<Item> items{ {1, 1}, {6, 2}, {18, 5}, {28, 7}, {22, 6} };
vector<Item> solution;
cout << "Max profit: " << Knapsack(items, 11, solution) << endl;
cout << "Items: " << endl;
for (auto a : solution)
cout << a.value << " " << a.weight << endl;
system("PAUSE");
return 0;
}

Reference:

http://www.cs.princeton.edu/~wayne/kleinberg-tardos/pdf/06DynamicProgrammingI.pdf

#### Geeks面试题：0-1 Knapsack Problem

2014-01-09 07:22:38

#### 0-1 Knapsack Problem

2017-04-10 09:59:14

#### 0-1背包问题（knapsack problem）

2012-06-10 20:05:42

#### [DP] 0-1 Knapsack Problem

2014-12-03 17:54:20

#### Knapsack problem (FZU_2214,福建省第六届ACM-problemC) 01背包+初始化问题+渐缩问题

2016-02-27 12:28:50

#### 背包问题(Knapsack problem)

2015-03-27 08:03:43

#### DP：背包问题 Knapsack Problem

2013-11-19 18:52:04

#### 0-1背包问题和部分背包(fractional knapsack)问题分析

2016-03-29 15:28:15

#### FZU 2214 Knapsack problem

2015-12-28 13:00:25

#### 算法/贪心算法/FractionalKnapsack部分背包问题

2017-04-24 18:46:42