-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathknapsackProblem.cpp
More file actions
42 lines (39 loc) · 881 Bytes
/
Copy pathknapsackProblem.cpp
File metadata and controls
42 lines (39 loc) · 881 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
#include <math.h>
#include <map>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<int> w(n + 1), c(n + 1);
for (int i = 1; i <= n; ++i) cin >> w[i];
for (int i = 1; i <= n; ++i) cin >> c[i];
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
vector<vector<bool>> p(n + 1, vector<bool>(m + 1));
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
dp[i][j] = dp[i - 1][j];
p[i][j] = 0;
if (j >= w[i] && dp[i - 1][j - w[i]] + c[i] > dp[i][j]) {
dp[i][j] = dp[i - 1][j - w[i]] + c[i];
p[i][j] = 1;
}
}
}
int cur_x = n, cur_y = m;
vector<int> ans;
while (cur_x > 0) {
if (p[cur_x][cur_y]) {
ans.push_back(cur_x);
cur_y -= w[cur_x];
}
cur_x--;
}
reverse(ans.begin(), ans.end());
for (int e : ans) {
cout << e << '\n';
}
}