hihoCoder 1043 完全背包

本文通过两段C++代码展示了如何解决无限背包问题,首先介绍了较为朴素的解法,然后进一步优化减少重复计算并节省空间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以直接在0-1背包的基础上进行扩展,得到一个比较naive的解法

// hiho1043.cpp : Defines the entry point for the console application.
//

#include<iostream>
#include<vector>
#include<algorithm>
#include<fstream>
//#define DEBUG

using namespace std;

int main()
{
#ifdef DEBUG
	ifstream cin("E:\\cppfiles\\input.txt");
#endif
	int n, m;
	cin >> n >> m;
	vector<int> need(n + 1, 0);
	vector<int> value(n + 1, 0);
	for (int i = 1; i <= n; ++i)
	{
		cin >> need[i] >> value[i];
	}
	vector<vector<int> > dp(n + 1, vector<int>(m + 1, 0));
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= m; ++j)
		{
			if (j < need[i])
			{
				dp[i][j] = dp[i - 1][j];
			}
			else
			{
				int cnt = 1;
				int tmp = 0;
				while (j - cnt*need[i] >= 0)
				{
					
					tmp = max(tmp, dp[i - 1][j - cnt*need[i]]+cnt*value[i]);
					cnt++;
				}
				dp[i][j] = max(dp[i - 1][j], tmp);
			}
		}
	}
	cout << dp[n][m] << endl;
	return 0;
}

注意观察可以得到,其实在每次计算i物品拿j件时,不需要从1开始循环,只要比较下拿j-1时即可,因为之前已经有计算好的结果了,如果从1开始循环,就进行了多余的重复计算。最后再进行空间的优化即可得到如下代码。

// hiho1043.cpp : Defines the entry point for the console application.
//

#include<iostream>
#include<vector>
#include<algorithm>
#include<fstream>
//#define DEBUG

using namespace std;

int main()
{
#ifdef DEBUG
	ifstream cin("E:\\cppfiles\\input.txt");
#endif
	int n, m;
	cin >> n >> m;
	vector<int> need(n + 1, 0);
	vector<int> value(n + 1, 0);
	for (int i = 1; i <= n; ++i)
	{
		cin >> need[i] >> value[i];
	}
	vector<int> dp(m + 1, 0);
	for (int i = 1; i <= n; ++i)
	{
		for (int j = need[i]; j <= m; ++j)
		{
			dp[j] = max(dp[j], dp[j-need[i]]+value[i]);
		}
	}
	cout << dp[m] << endl;
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值