朴素算法:
//01背包问题 f[i][j] = max(f[i - 1][j], f[i - 1][j - v] + w);
//完全背包问题 f[i][j] = max(f[i][j], f[i][j - v] + w);
#include <iostream>
using namespace std;
const int N = 1010;
int f[N][N], v[N], w[N];
int n, m;
int main()
{
cin >> n >> m;
for(int i = 1; i <= n; i++)
cin >> v[i] >> w[i];
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= m ; j++)
{
f[i][j] = f[i - 1][j];
if(j >= v[i])
f[i][j] = max(f[i][j], f[i][j - v[i]] + w[i]);
}
cout << f[n][m];
return 0;
}
优化:
#include <iostream>
using namespace std;
const int N = 1010;
int f[N], v[N], w[N];
int n, m;
int main()
{
cin >> n >> m;
for(int i = 1; i <= n; i++) cin >> v[i] >> w[i];
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
{
f[j] = f[j]; //先算i - 1所以也是先被算过的,可以直接去掉一层
if(j >= v[i]) f[j] = max(f[j], f[j - v[i]] + w[i]); // 因为 j - v[i] < j 所以f[j - v[i]]是已经被算过的,即第i层
}
cout << f[m];
return 0;
}