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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值