dp[i][j] = max{dp[i - 1][j], dp[i - 1][j - c[i] + w[i]]}
for i in 0 ... N for v = V ... 0 f[v] = max{f[v], f[v-c[i]] + w[i]}
#include <stdio.h> #include <stdlib.h> #include <string.h> #define N 1010 int value[N], volume[N], dp[N]; // 0-1背包,优化空间 void dpPackage(int n, int v) { int i, j; memset(dp, 0, sizeof(dp)); for (i = 1; i <= n; i ++) { for (j = v; j >= volume[i]; j --) { dp[j] = dp[j] > dp[j - volume[i]] + value[i] ? dp[j] : dp[j - volume[i]] + value[i]; } } printf("%d\n", dp[v]); } int main(void) { int i, t, n, v; scanf("%d", &t); while (t --) { // 接收参数 scanf("%d %d", &n, &v); for (i = 1; i <= n; i ++) scanf("%d", value + i); for (i = 1; i <= n; i ++) scanf("%d", volume + i); // 0-1背包 dpPackage(n, v); } return 0; }
dp[i][v] = max{dp[i-1][v - k * c[i]] + k * w[i] | 0 <= k * c[i]<= v}
for i = 1 ... N for v = 0 ... V f[v] = max{f[v], f[v-cost] + weight}
/** * 完全背包问题 */ #include <stdio.h> #include <stdlib.h> #define INF 50000000 typedef struct coin { int price, weight; } coin; void dynamicPackage(coin *coins, int n, int v) { if (v < 0) { printf("This is impossible.\n"); return; } int i, j, *dp; // 动态分配内存 dp = (int *)malloc(sizeof(int) * (v + 1)); // 初始化 dp[0] = 0; for (i = 1; i <= v; i ++) dp[i] = INF; // 完全背包问题 for (i = 1; i <= n; i ++) { for (j = coins[i].weight; j <= v; j ++) { dp[j] = (dp[j] < dp[j - coins[i].weight] + coins[i].price) ? dp[j] : dp[j - coins[i].weight] + coins[i].price; } } if (dp[v] >= INF) printf("This is impossible.\n"); else printf("The minimum amount of money in the piggy-bank is %d.\n", dp[v]); // 清理内存 free(dp); dp = NULL; } int main(void) { int t, e, f, n, i; coin *coins; scanf("%d", &t); while (t --) { scanf("%d %d", &e, &f); scanf("%d", &n); // 接收货币 coins = (coin *)malloc(sizeof(coin) * (n + 1)); if (coins == NULL) exit(-1); for (i = 1; i <= n; i ++) { scanf("%d %d", &coins[i].price, &coins[i].weight); } // 完全背包 dynamicPackage(coins, n, f - e); free(coins); coins = NULL; } return 0; }
dp[i][v] = max{dp[i - 1][v - k * c[i]] + w[i] | 0 <=k <= n[i]}
#include <stdio.h> #include <stdlib.h> typedef struct rice { int price, weight, num; } rice; void dynamic(rice *rices, int m, int n) { int i, j, cur, k, **dp; // 动态申请二维数组 dp = (int **)malloc(sizeof(int *) * (m + 1)); for (i = 0; i <= m; i ++) dp[i] = (int *)malloc(sizeof(int) * (n + 1)); // 初始化 for (i = 0; i <= m; i ++) for (j = 0; j <= n; j ++) dp[i][j] = 0; // 动态规划 for (i = 1; i <= m; i ++) { for (j = 1; j <= n; j ++) { for (k = 0; k <= rices[i].num; k ++) { if (j - k * rices[i].price >= 0) { cur = dp[i - 1][j - k * rices[i].price] + k * rices[i].weight; dp[i][j] = dp[i][j] > cur ? dp[i][j] : cur; } else { break; } } } } printf("%d\n", dp[m][n]); for (i = 0; i <= m; i ++) free(dp[i]); } int main(void) { int i, c, n, m; rice rices[2010]; scanf("%d", &c); while (c --) { scanf("%d %d", &n, &m); // 接收数据 for (i = 1; i <= m; i ++) { scanf("%d %d %d", &rices[i].price, &rices[i].weight, &rices[i].num); } // 多重背包问题 dynamic(rices, m, n); } return 0; }