解题思路
完全背包问题
优化思路,对状态转移做等价变形
1. f(i, j) = f(i - 1, j) + f(i - 1, j - a[i]) + f(i - 1, j - 2 * a[i]) ...
2. f(i, j - a[i]) = f(i - 1, j - a[i]) + f(i - 1, j - 2 * a[i]) ...
3. f(i, j) = f(i - 1, j) + f(i, i - a[i]);
代码
原始做法 O(N^3)
#include <iostream>
using namespace std;
const int N = 20, M = 3010;
int a[N];
long f[N][M];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
f[0][0] = 1;
for (int i = 1; i <= n; i++) {
f[i][0] = 1;
for (int j = 1; j <= m; j++) {
for (int k = 0; j >= k * a[i]; k++) {
f[i][j] += f[i - 1][j - k * a[i]];
}
}
}
cout << f[n][m] << endl;
return 0;
}
优化时间 O(N^2)
#include <iostream>
using namespace std;
const int N = 20, M = 3010;
int a[N];
long f[N][M];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
f[0][0] = 1;
for (int i = 1; i <= n; i++) {
f[i][0] = 1;
for (int j = 1; j <= m; j++) {
f[i][j] = f[i - 1][j];
if (j >= a[i]) f[i][j] += f[i][j - a[i]];
}
}
cout << f[n][m] << endl;
return 0;
}
优化空间
#include <iostream>
using namespace std;
const int N = 20, M = 3010;
int a[N];
long f[M];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
f[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = a[i]; j <= m; j++) f[j] += f[j - a[i]];
}
cout << f[m] << endl;
return 0;
}