0-1背包问题c++代码
时间: 2024-01-15 22:19:09 浏览: 88
回溯算法 0-1 背包算法
以下是一个用C++实现的0-1背包问题的代码示例:
```cpp
#include <iostream>
using namespace std;
int knapSack(int W, int wt[], int val[], int n) {
int dp[n + 1][W + 1];
for (int i = 0; i <= n; i++) {
for (int w = 0; w <= W; w++) {
if (i == 0 || w == 0)
dp[i][w] = 0;
else if (wt[i - 1] <= w)
dp[i][w] = max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]);
else
dp[i][w] = dp[i - 1][w];
}
}
return dp[n][W];
}
int main() {
int val[] = {60, 100, 120};
int wt[] = {10, 20, 30};
int W = 50;
int n = sizeof(val) / sizeof(val[0]);
cout << "Maximum value: " << knapSack(W, wt, val, n) << endl;
return 0;
}
```
阅读全文