你会发现
对于这种很像背包的DP。。。不打滚动数组很有可能错,因为很多时候可能会忘记保留以前状态的答案,体现在f[i][j] = max(f[i-1][j], f[i][j]);上,因为f[i][j]可能被f[i][b[i]]更新,所以要取max,若想不取max,则必须保证这个状态只会被更新一次
这题刷表比填表更好写,刷表你的初始化只需要让f[0] = 1 然后用目前的0去更新其他状态
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <map>
using namespace std;
#define debug(x) cerr << #x << "=" << x << endl;
const int MAXN = 2005;
const int MOD = 1000000000 + 7;
int n,ans,a[30],m,vis_c[30],vis_w[30],hshtemp[MAXN],b[MAXN],f[MAXN],tot;
int calc() {
int now = 0, sum = 0;
for(int i=1; i<=n; i++) {
if(!vis_c[i]) {
b[++now] = a[i];
}
}
memset(f, 0, sizeof(f));
f[0] = 1;
tot = 0;
for(int i=1; i<=n; i++) {
if(vis_c[i]) continue;
for(int j=tot; j>=0; j--) {
if(f[j]) f[j+a[i]] = 1, f[j] = 1;
}
tot += a[i];
}
/* for(int i=1; i<=now; i++) { // 阶段
f[i][b[i]] = 1;
tot += b[i];
for(int j=tot; j>=1; j--){ //决策
f[i][j] = max(f[i-1][j], f[i][j]);
if(j >= b[i])
f[i][j] = max(f[i-1][j-b[i]], f[i][j]);
}
}*/
for(int i=1; i<=tot; i++)
if(f[i]) sum++;
return sum;
}
void dfs_c(int x, int now, int m) {
if(now == m && x == n+1) {
ans = max(ans, calc());
return;
}
if(now > m || x >= n+1) return;
if(!vis_c[x]) {
vis_c[x] = 1;
dfs_c(x+1, now+1, m);
vis_c[x] = 0;
}
dfs_c(x+1, now, m);
}
int main() {
scanf("%d %d", &n, &m);
for(int i=1; i<=n; i++) {
scanf("%d", &a[i]);
}
dfs_c(1, 0, m);
printf("%d\n", ans);
return 0;
}

本文深入探讨了使用动态规划解决背包问题的技巧,特别是在避免错误保留状态答案方面,通过实例讲解了如何利用滚动数组来优化算法,并给出了具体的C++实现代码。
503

被折叠的 条评论
为什么被折叠?



