-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrackanppsack.cpp
More file actions
72 lines (61 loc) · 1.68 KB
/
frackanppsack.cpp
File metadata and controls
72 lines (61 loc) · 1.68 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
#include <iostream>
using namespace std;
class Item {
public:
int weight, value;
double ratio;
};
class FractionalKnapsack {
Item *items;
int n;
public:
FractionalKnapsack(int size) {
n = size;
items = new Item[n];
}
void inputItems() {
cout << "Enter weight and value for each item:\n";
for (int i = 0; i < n; i++) {
cin >> items[i].weight >> items[i].value;
items[i].ratio = (double)items[i].value / items[i].weight;
}
}
void sortItems() {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (items[j].ratio < items[j + 1].ratio) {
swap(items[j], items[j + 1]);
}
}
}
}
double knapsack(int capacity) {
sortItems();
double maxValue = 0.0;
for (int i = 0; i < n; i++) {
if (capacity >= items[i].weight) {
maxValue += items[i].value;
capacity -= items[i].weight;
} else {
maxValue += items[i].ratio * capacity;
break;
}
}
return maxValue;
}
~FractionalKnapsack() {
delete[] items;
}
};
int main() {
int n, capacity;
cout << "Enter number of items: ";
cin >> n;
FractionalKnapsack fk(n);
fk.inputItems();
cout << "Enter knapsack capacity: ";
cin >> capacity;
cout << "Maximum value in knapsack: " << fk.knapsack(capacity) << endl;
return 0;
}
//This program sorts items by value-to-weight ratio and adds them fractionally to maximize the knapsack's value. Let me know if you need modifications!