-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnbounded_Knapsack.cpp
More file actions
59 lines (53 loc) · 1.05 KB
/
Copy pathUnbounded_Knapsack.cpp
File metadata and controls
59 lines (53 loc) · 1.05 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
#include<bits/stdc++.h>
using namespace std;
int unbounded_knapsack(int weight[],int value[],int n,int W)
{
int K[W+1];
K[0]=0;
for(int x=1;x<=W;++x)
{
K[x]=0;
for(int i=0;i<n;++i)
{
int w = weight[i];
int v = value[i];
if(w<= x)
{
K[x]= max(K[x],K[x-w]+v);
}
}
}
return K[W];
}
int unboundedKnapsack(int W, int n, int val[], int wt[])
{
// dp[i] is going to store maximum value
// with knapsack capacity i.
int dp[W+1];
//memset(dp, 0, sizeof dp);
dp[0]=0;
// int ans = 0;
// Fill dp[] using above recursive formula
for (int i=1; i<=W; i++) //or i= 1;
{
dp[i]=0;
for (int j=0; j<n; j++)
{
int w = wt[j];
int v = val[j];
if (w <= i)
dp[i] = max(dp[i], dp[i-wt[j]]+v);
}
}
return dp[W];
}
int main()
{
int W = 100;
int val[] = {10, 30, 20};
int wt[] = {5, 10, 15};
int n = sizeof(val)/sizeof(val[0]);
cout << unbounded_knapsack(wt, val, n, W);
//cout << unboundedKnapsack(W, n, val, wt);
return 0;
}