可以直接在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;
}