【发布时间】:2020-05-14 14:38:20
【问题描述】:
我正在尝试解决大重量问题的 0-1 背包。问题的约束是:
- *输入中的所有值都是整数。
- $$1 \leq N \leq 100$$
- $$1 \leq W \leq 10^9$$
- $$1 \leq w_i \leq W$$
- $$1 \leq v_i \leq 10^3*$$
以下是我用 cmets 编写的代码。
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
const int V = 1e5;
const int N = 100;
int main() {
int n, w, inp1, inp2, max_val = -1;
vector<pair<int, int>> arr;
cin >> n >> w; // n - no of items, w - total weight that the knapsack can hold
for(int i = 0; i < n; i++){
cin >> inp1 >> inp2; // ith input : w_i v_i
arr.push_back({inp1, inp2});
max_val = max(max_val, inp2); // storing maximum value of an item from the inputs
}
unsigned long long int dp[N + 1][V + 1]; // dp[i][j] = min weight that can be obtained from items 0..(i - 1) having total value atmost j
for(int i = 0; i <= n; i++){
for(int j = 0; j <= (max_val * n); j++){
if(i == 0 || j == 0)
dp[i][j] = ULLONG_MAX;
else if(j >= arr[i].second)
dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - arr[i - 1].second] + arr[i - 1].first);
else
dp[i][j] = dp[i - 1][j];
}
}
for(int i = 0; i <= n; i++){
for(int j = 0; j <= (max_val * n); j++)
cout << dp[i][j] << " ";
cout << endl;
}
int i;
for(i = (max_val * n); i >= 1; i--){
if(dp[n][i] != ULLONG_MAX && dp[n][i] <= w)
break;
}
cout << i;
return 0;
}
但我没有得到所有输入的正确答案。例如,对于输入
3 8
3 30
4 50
5 60
我得到 180 作为答案,而 90 是准确的答案。请帮我解决它。
【问题讨论】:
标签: c++ dynamic-programming knapsack-problem