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

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/KusanoNEU/article/details/51554698
文章标签: Knapsack with dynami
个人分类: 算法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭