「BZOJ 4247」挂饰

题目大意:

$f[i][j]$ 表示前 $i$ 个物品还有 $j$ 个空挂钩的最大价值。

注意先按照每个物品的挂钩数从大到小排序,不然两个本来可以一起挂上的物品会被误判断为只能挂一个。

#include <cstdio>
#include <cstring>
#include <algorithm>

const int N = 2005;
int n, f[N][N], ans;
struct Node {
    int a, b;
    bool operator < (const Node &rhs) const {
        return a > rhs.a;
    }
} c[N];

int max(int x, int y) {
    return x > y ? x : y;
}

int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) scanf("%d%d", &c[i].a, &c[i].b);
    std::sort(c + 1, c + n + 1);
    memset(f, 128, sizeof f);
    f[0][1] = 0;
    for (int i = 1; i <= n; ++i) { //前i个物品
        f[i][n] = f[i-1][n];
        for (int j = n - c[i].a + 1; j <= n; ++j)
            f[i][n] = max(f[i][n], f[i-1][j] + c[i].b);
        for (int j = 0; j < n; ++j) { //空挂钩的数量
            f[i][j] = f[i-1][j];
            if (j >= c[i].a - 1) f[i][j] = max(f[i][j], f[i-1][j-c[i].a+1] + c[i].b);
        }
    }
    for (int j = 0; j <= n; ++j) ans = max(ans, f[n][j]);
    printf("%d\n", ans);
    return 0;
}