请帮我用c++写出01背包问题的模板
时间: 2024-05-09 12:21:30 浏览: 67
背包问题(用c++)
当然可以!以下是01背包问题的C语言模板:
```
#include <stdio.h>
int max(int a, int b) {
return (a > b) ? a : b;
}
int knapSack(int W, int wt[], int val[], int n) {
int i, j;
int K[n+1][W+1];
for (i = 0; i <= n; i++) {
for (j = 0; j <= W; j++) {
if (i == 0 || j == 0)
K[i][j] = 0;
else if (wt[i-1] <= j)
K[i][j] = max(val[i-1] + K[i-1][j-wt[i-1]], K[i-1][j]);
else
K[i][j] = K[i-1][j];
}
}
return K[n][W];
}
int main() {
int val[] = {60, 100, 120};
int wt[] = {10, 20, 30};
int W = 50;
int n = sizeof(val)/sizeof(val[0]);
printf("Maximum value: %d\n", knapSack(W, wt, val, n));
return 0;
}
```
希望这个模板对你有所帮助!
阅读全文