-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlab06_sum_of_subset_using_0-1_knapsack.cpp
56 lines (45 loc) · 1.24 KB
/
lab06_sum_of_subset_using_0-1_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>
using namespace std;
bool knapsack(vector<int> p, vector<int> w, int cap, int max_profit) {
int n = p.size();
vector<vector<int>> dp(n+1, vector<int>(cap+1, 0));
for(int i=1 ; i<=n ; i++) {
for(int j=1 ; j<=cap ; j++) {
if(j<w[i]) {
dp[i][j] = dp[i-1][j];
}
else {
dp[i][j] = max(dp[i-1][j], p[i]+dp[i-1][j-w[i]]);
}
}
}
if(dp[n][cap] >= max_profit) { // dp[n][cap] will never be greater than max_profit because cap is same as max_profit
return true;
}
else {
return false;
}
}
void sum_of_subset(vector<int> arr, int sum) {
if(knapsack(arr, arr, sum, sum) == true) {
cout << "Subset is present in arr with sum : " << sum << endl;
}
else {
cout << "Subset is not present in arr with sum : " << sum << endl;
}
}
int main() {
int n;
cout << "Number of element present in array : ";
cin >> n;
cout << "Enter all element : ";
vector<int> arr(n);
for(int i=0 ; i<n ; i++) {
cin >> arr[i];
}
int sum;
cout << "Required sum : ";
cin >> sum;
sum_of_subset(arr, sum);
return 0;
}