c语言不考虑价值背包问题
时间: 2023-12-24 15:25:40 浏览: 63
背包问题(C语言)
以下是C语言中不考虑价值的背包问题的解法:
```c
#include <stdio.h>
#include <stdlib.h>
int max(int x, int y) {
if (x >= y) {
return x;
} else {
return y;
}
}
int knapsack(int *m, int n, int w) {
int i, j;
int **dp = (int **)malloc((n + 1) * sizeof(int *));
for (i = 0; i <= n; i++) {
dp[i] = (int *)malloc((w + 1) * sizeof(int));
}
for (i = 0; i <= n; i++) {
for (j = 0; j <= w; j++) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
} else if (m[i - 1] <= j) {
dp[i][j] = max(m[i - 1] + dp[i][j - m[i - 1]], dp[i - 1][j]);
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
int result = dp[n][w];
for (i = 0; i <= n; i++) {
free(dp[i]);
}
free(dp);
return result;
}
int main() {
int n, w, i;
printf("背包问题\n");
printf("输入物品种数:");
scanf("%d", &n);
int *m = (int *)malloc(n * sizeof(int));
printf("输入物品重量:");
for (i = 0; i < n; i++) {
scanf("%d", &m[i]);
}
printf("输入背包容量:");
scanf("%d", &w);
int result = knapsack(m, n, w);
printf("最大可装重量为:%d\n", result);
free(m);
return 0;
}
```
阅读全文