分组背包,如果分成01背包有可能会超限,使用二进制分组的方法
比如18=1+2+4+8+3
分解成二进制的大物品
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> using namespace std; int max(int a, int b){ return a > b ? a : b; } int main() { int n, m; cin >> n >> m; int cost[100001] = { 0 }; int value[100001] = { 0 }; int ans = 0; for (int i = 0; i < n; i++){ int a, b, c; cin >> b >> a >> c; int t = 1; while (c - t>0){ c -= t; cost[ans] = t*a; value[ans++] = t*b; t *= 2; } cost[ans] = c*a; value[ans++] = c*b; } int pos[40001] = { 0 }; for (int i = 0; i < ans; i++){ for (int j = m; j >= cost[i]; j--){ pos[j] = max(pos[j], pos[j - cost[i]] + value[i]); } } cout << pos[m] << endl; return 0; }
原文:https://www.cnblogs.com/Vetsama/p/12288484.html