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

解题思路:

所谓分组背包,就是将物品分组,每组的物品相互冲突,最多只能选一个物品放进去。

这种题怎么想呢?其实是从「在所有物品中选择一件」变成了「从当前组中选择一件」,于是就对每一组进行一次 0-1 背包就可以了。

示例代码:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1010;
struct Node {
int c, v;
Node() {};
Node(int _c, int _v) { c = _c; v = _v; }
};
map<int, vector<Node> > groups;
int n, m, f[maxn];
int main() {
cin >> m >> n;
for (int i = 0; i < n; i ++) {
int a, b, c;
cin >> a >> b >> c;
groups[c].push_back(Node(a, b));
}
for (map<int, vector<Node> >::iterator it = groups.begin(); it != groups.end(); it ++) {
vector<Node> group = it->second;
int sz = group.size();
for (int i = m; i >= 0; i --) {
for (int j = 0; j < sz; j ++) {
int c = group[j].c, v = group[j].v;
if (i >= c) f[i] = max(f[i], f[i-c] + v);
}
}
}
cout << f[m] << endl;
return 0;
}