算法一:动态二维数组
#include <iostream>
using namespace std;
const int N = 20010;
int f[N][N];
int n, m;
int v[N];
int main()
{
cin >> m >> n;
for(int i = 1; i <= n; i++)
cin >> v[i];
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j ++)
{
f[i][j] = f[i - 1][j]; // 不选i
if(j >= v[i])
f[i][j] = max(f[i][j], f[i - 1][j - v[i]] + v[i]); 选i
}
int res = 0;
for(int i = 0; i <= m; i ++) res = max(f[n][i],res);
cout << m - res;
return 0;
}
优化:
#include <iostream>
using namespace std;
const int N = 20010;
int f[N];
int n, m;
int v[N];
int main()
{
cin >> m >> n;
for(int i = 1; i <= n; i++)
cin >> v[i];
for(int i = 1; i <= n; i++)
for(int j = m; j >= v[i]; j --)
f[j] = max(f[j], f[j - v[i]] + v[i]);
int res = 0;
for(int i = 0; i <= m; i ++) res = max(f[i],res);
cout << m - res;
return 0;
}