-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathknapsack01.cpp
More file actions
67 lines (66 loc) · 2 KB
/
knapsack01.cpp
File metadata and controls
67 lines (66 loc) · 2 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <bits/stdc++.h>
#include <limits.h>
using namespace std;
pair<int, vector<int>> knapsack(int W, int N, int* weight, int* value);
int main(){
int W, N;
cin >> W >> N;
int weight[N], value[N];
for (int i = 0; i < N; i ++){
cin >> weight[i];
}
for (int i = 0; i < N; i ++){
cin >> value[i];
}
pair<int, vector<int> > ans = knapsack(W, N, weight, value);
cout << ans.first << endl;
for (int i = 0; i < ans.second.size(); i ++){
cout << ans.second[i] << " ";
}
}
pair<int, vector<int>> knapsack(int W, int N, int* weight, int* value){
int current_weight = W, inx_item = N;
int** arr; int** isselect;
vector<int> index;
arr = new int* [N+1];
isselect = new int* [N+1];
for (int i = 0; i <= N; i ++){
arr[i] = new int [W+1];
isselect[i] = new int [W+1];
}
for (int i = 0; i <= N; i ++){
for (int j = 0; j <= W; j ++){
arr[i][j] = 0;
isselect[i][j] = 0;
}
}
for (int i = 1; i <= N; i ++){
for (int j = 1; j <= W; j ++){
if (j < weight[i-1]){
arr[i][j] = arr[i-1][j];
isselect[i][j] = 0;
} else {
if (arr[i-1][j] < value[i-1] + arr[i-1][j-weight[i-1]]){
arr[i][j] = value[i-1] + arr[i-1][j-weight[i-1]];
isselect[i][j] = 1;
} else {
arr[i][j] = arr[i-1][j];
isselect[i][j] = 0;
}
}
}
}
while (current_weight > 0 && inx_item > 0){
if (isselect[inx_item][current_weight] == 1){
index.push_back(inx_item);
current_weight -= weight[inx_item-1];
inx_item -= 1;
} else {
inx_item -= 1;
}
}
sort(index.begin(), index.end());
pair<int, vector<int> > ans = make_pair(arr[N][W], index);
return ans;
}