P1441 砝码称重 - 搜索+dp

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Fantasy_World/article/details/82503149

你会发现
对于这种很像背包的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去更新其他状态
总结出DP的写法:

刷表

等式左边是用来刷的状态,右边是要更新的状态

填表

等式左边是要更新的状态,右边是要更新的状态的来源

#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[30][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];
    }*/
    tot = 0;
    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[now][i]) sum++;
    return sum;
}

void dfs_c(int x, int now, int m) {
    if(now > m || now + n - x + 1 < m) return;
    if(x == n+1) {
        ans = max(ans, calc());
        return;
    }
    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;
}

猜你喜欢

转载自blog.csdn.net/Fantasy_World/article/details/82503149