-
Notifications
You must be signed in to change notification settings - Fork 47
/
Knapsack.cpp
56 lines (47 loc) Β· 866 Bytes
/
Knapsack.cpp
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
#include <bits/stdc++.h>
#define N 105
#define WMAX 205
struct item{
int profit;
int weight;
};
using namespace std;
item arr[N];
int M[N][WMAX];
void find_solution(int i, int w){
if (i == 0){
return;
}
if (M[i][w] == M[i-1][w]){
find_solution(i-1, w);
}
else{
find_solution(i-1, w - arr[i].weight);
printf("%d " ,i );
}
}
int main(){
int n, p, W;
scanf("%d %d" ,&n ,&W);
for (int i = 1; i <= n; i++){
scanf("%d %d" ,&arr[i].profit ,&arr[i].weight);
}
for (int i = 0; i <= W; i++){
M[0][i] = 0;
}
for (int i = 1; i <= n; i++){
for (int w_ = 1; w_ <= W; w_++){
if (arr[i].weight > w_){
M[i][w_] = M[i-1][w_];
}
else{
M[i][w_] = max(M[i-1][w_], arr[i].profit + M[i-1][w_ - arr[i].weight]);
}
}
}
printf("profit: %d\n" ,M[n][W]);
printf("solution set: ");
find_solution(n, W);
printf("\n");
return 0;
}