-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01knapsack(branch&bound).cpp
More file actions
134 lines (104 loc) ยท 2.65 KB
/
01knapsack(branch&bound).cpp
File metadata and controls
134 lines (104 loc) ยท 2.65 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <bits/stdc++.h>
using namespace std;
struct Item
{
int value;
float weight;
};
struct Node
{
int level, profit, bound;
float weight;
};
class knap
{
public:
int bound(Node u, int n, int W, Item arr[]);
int knapsack(int W, Item arr[], int n);
};
static bool cmp(Item a, Item b)
{
double r1 = (double)a.value / a.weight;
double r2 = (double)b.value / b.weight;
return r1 > r2;
}
int knap::bound(Node u, int n, int W, Item arr[])
{
if (u.weight >= W)
return 0;
int profit_bound = u.profit;
int j = u.level + 1;
int totweight = u.weight;
while ((j < n) && (totweight + arr[j].weight <= W))
{
totweight += arr[j].weight;
profit_bound += arr[j].value;
j++;
}
if (j < n)
profit_bound += (W - totweight) * arr[j].value /
arr[j].weight;
return profit_bound;
}
int knap::knapsack(int W, Item arr[], int n)
{
std::sort(arr, arr + n, cmp);
queue<Node> Q;
Node u, v;
u.level = -1;
u.profit = u.weight = 0;
Q.push(u);
int maxProfit = 0;
while (!Q.empty())
{
u = Q.front();
Q.pop();
if (u.level == -1)
v.level = 0;
if (u.level == n-1)
continue;
v.level = u.level + 1;
v.weight = u.weight + arr[v.level].weight;
v.profit = u.profit + arr[v.level].value;
if (v.weight <= W && v.profit > maxProfit)
maxProfit = v.profit;
v.bound = bound(v, n, W, arr);
if (v.bound > maxProfit)
Q.push(v);
v.weight = u.weight;
v.profit = u.profit;
v.bound = bound(v, n, W, arr);
if (v.bound > maxProfit)
Q.push(v);
}
return maxProfit;
}
int main()
{
knap K;
int W, n;
cout<<"\nEnter Knapsack Capacity : ";
cin>>W;
Item arr[20];
cout<<"\nEnter number of items : ";
cin>>n;
cout<<endl;
for(int i=0; i<n;i++)
{
cout<<"Enter value of item "<<i+1<<" :";
cin>>arr[i].value;
cout<<"Enter weight of item "<<i+1<<" :";
cin>>arr[i].weight;
cout<<endl;
}
//int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum possible profit = "
<< K.knapsack(W, arr, n);
cout<<endl;
return 0;
}
/*OUTPUT
D:\Data\Downloads\DAA Codes>g++ knapsack.cpp
D:\Data\Downloads\DAA Codes>a
Maximum possible profit = 235
*/