洛谷P5662 纪念品 题解 完全背包

题目链接:https://www.luogu.com.cn/problem/P5662

解题思路:

我们进行 (t−1)完全背包 :

  • 把今天手里的钱当做背包的容量,
  • 把商品今天的价格当成它的消耗,
  • 把商品明天的价格当做它的价值。

示例代码:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 110, maxm = 10010;
int t, n, m, ans, p[maxn][maxm], f[maxm], V[maxn];
void comp_pack(int d) {  // d表示第d天
    for (int i = 1; i <= V[d-1]; i ++) f[i] = i;
    for (int i = 1; i <= n; i ++) // 遍历n件物品
        for (int j = p[d-1][i]; j <= V[d-1]; j ++)
            f[j] = max(f[j], f[j-p[d-1][i]]+p[d][i]);
    V[d] = f[V[d-1]];
    ans = max(ans, V[d]);
}
int main() {
    cin >> t >> n >> m;
    for (int i = 1; i <= t; i ++)
        for (int j = 1; j <= n; j ++)
            cin >> p[i][j];
    ans = V[1] = m;
    for (int i = 2; i <= t; i ++) comp_pack(i);
    cout << ans << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/quanjun/p/13638260.html