动态规划0-1背包问题c
时间: 2023-11-08 11:05:49 浏览: 91
动态规划-0-1背包问题
好的,关于动态规划0-1背包问题的C语言实现,可以参考以下代码:
```c
#include <stdio.h>
#define MAX_N 100
#define MAX_W 1000
int n, W;
int w[MAX_N], v[MAX_N];
int dp[MAX_N+1][MAX_W+1];
int max(int a, int b) {
return a > b ? a : b;
}
int main() {
scanf("%d %d", &n, &W);
for (int i = 0; i < n; i++) {
scanf("%d %d", &w[i], &v[i]);
}
for (int i = n-1; i >= 0; i--) {
for (int j = 0; j <= W; j++) {
if (j < w[i]) {
dp[i][j] = dp[i+1][j]; } else {
dp[i][j] = max(dp[i+1][j], dp[i+1][j-w[i]] + v[i]);
}
}
}
printf("%d\n", dp[0][W]);
return 0;
}
```
阅读全文