1 // 01背包 ========================================== 2 3 memset(f, 0xcf, sizeof(f)); // -INF 4 f[0][0] = 0; 5 for (int i = 1; i <= n; i++) { 6 for (int j = 0; j <= m; j++) 7 f[i][j] = f[i - 1][j]; 8 for (int j = v[i]; j <= m; j++) 9 f[i][j] = max(f[i][j], f[i - 1][j - v[i]] + w[i]); 10 } 11 12 int f[2][MAX_M+1]; 13 memset(f, 0xcf, sizeof(f)); // -INF 14 f[0][0] = 0; 15 for (int i = 1; i <= n; i++) { 16 for (int j = 0; j <= m; j++) 17 f[i & 1][j] = f[(i - 1) & 1][j]; 18 for (int j = v[i]; j <= m; j++) 19 f[i & 1][j] = max(f[i & 1][j], f[(i - 1) & 1][j - v[i]] + w[i]); 20 } 21 int ans = 0; 22 for (int j = 0; j <= m; j++) 23 ans = max(ans, f[n & 1][j]); 24 25 int f[MAX_M+1]; 26 memset(f, 0xcf, sizeof(f)); // -INF 27 f[0] = 0; 28 for (int i = 1; i <= n; i++) 29 for (int j = m; j >= v[i]; j--) 30 f[j] = max(f[j], f[j - v[i]] + w[i]); 31 int ans = 0; 32 for (int j = 0; j <= m; j++) 33 ans = max(ans, f[j]); 34 35 36 // 完全背包 ========================================== 37 38 int f[MAX_M+1]; 39 memset(f, 0xcf, sizeof(f)); // -INF 40 f[0] = 0; 41 for (int i = 1; i <= n; i++) 42 for (int j = v[i]; j <= m; j--) 43 f[j] = max(f[j], f[j - v[i]] + w[i]); 44 int ans = 0; 45 for (int j = 0; j <= m; j++) 46 ans = max(ans, f[j]); 47 48 49 // 多重背包,直接拆分 ========================================== 50 51 unsigned int f[MAX_M+1]; 52 memset(f, 0xcf, sizeof(f)); // -INF 53 f[0] = 0; 54 for (int i = 1; i <= n; i++) 55 for (int j = 1; j <= c[i]; j++) 56 for (int k = m; k >= v[i]; k--) 57 f[k] = max(f[k], f[k - v[i]] + w[i]); 58 int ans = 0; 59 for (int i = 0; i <= m; i++) 60 ans = max(ans, f[i]); 61 62 // 分组背包 ========================================== 63 64 memset(f, 0xcf, sizeof(f)); 65 f[0] = 0; 66 for (int i = 1; i <= n; i++) 67 for (int j = m; j >= 0; j--) 68 for (int k = 1; k <= c[i]; k++) 69 if (j >= v[i][k]) 70 f[j] = max(f[j], f[j - v[i][k]] + w[i][k]);