01背包问题动态规划用c++实现
时间: 2023-11-20 08:59:33 浏览: 67
c++用动态规划实现01背包问题
5星 · 资源好评率100%
以下是使用动态规划解决01背包问题的C++代码实现:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int max(int a, int b) {
return (a > b) ? a : b;
}
int knapSack(int m, int n, int a[], int p[]) {
int dp[n + 1][m + 1];
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (a[i - 1] > j) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - a[i - 1]] + p[i - 1]);
}
}
}
return dp[n][m];
}
int main() {
int m = 50;
int n = 3;
int a[] = {10, 20, 30};
int p[] = {60, 100, 120};
cout << "Max value: " << knapSack(m, n, a, p) << endl;
return 0;
}
```
阅读全文