关闭

Knapsack problem I

标签: Knapsack with dynami
140人阅读 评论(0) 收藏 举报
分类:
#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

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:10418次
    • 积分:619
    • 等级:
    • 排名:千里之外
    • 原创:54篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章分类