动态规划求01背包c语言
时间: 2023-12-11 08:32:54 浏览: 72
以下是用C语言实现的基于动态规划求解01背包问题的代码,其中假设背包容量为V,物品数量为n,重量数组为w,价值数组为v:
```c
#include <stdio.h>
#include <stdlib.h>
int max(int a, int b) {
return a > b ? a : b;
}
int knapsack(int V, int n, int w[], int v[]) {
int dp[n + 1][V + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= V; j++) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
} else if (w[i - 1] <= j) {
dp[i][j] = max(v[i - 1] + dp[i - 1][j - w[i - 1]], dp[i - 1][j]);
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[n][V];
}
int main() {
int V = 10;
int n = 5;
int w[] = {2, 1, 3, 2, 1};
int v[] = {12, 10, 20, 15, 5};
printf("Max value: %d\n", knapsack(V, n, w, v));
return 0;
}
```
阅读全文