动态规划--0-1背包问题代码实现
代码实现0/1背包
#include<stdio.h>
#define N 4
#define W 5
int max(int a, int b) {
return a > b ? a : b;
}
int main() {
int v[] = { 0,2,4,5,6 };
int w[] = { 0,1,2,3,4 };
int f[N + 1][W + 1] = {0};
int i, j;
for (i = 1; i <= N; i++) {
for (j = 1; j <= W; j++) {
f[i][j] = f[i - 1][j];
if (j >= w[i]) {
f[i][j] = max(f[i][j], f[i - 1][j - w[i]] + v[i]);
}
}
}
printf("%d\n", f[N][W]);
for (i = 0; i <= N; i++) {
for (j = 0; j <= W; j++) {
printf("%d ", f[i][j]);
}
printf("\n");
}
return 0;
}