-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrackanp.cpp
More file actions
64 lines (53 loc) · 1.39 KB
/
frackanp.cpp
File metadata and controls
64 lines (53 loc) · 1.39 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
#include <iostream>
using namespace std;
class Item {
public:
int weight, value;
float ratio;
void set(int w, int v) {
weight = w;
value = v;
ratio = (float)v / w;
}
};
void fractionalKnapsack(int n, int capacity, Item *items) {
// Sort by ratio in descending order
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (items[i].ratio < items[j].ratio) {
Item temp = items[i];
items[i] = items[j];
items[j] = temp;
}
}
}
float totalValue = 0;
int remaining = capacity;
for (int i = 0; i < n && remaining > 0; i++) {
if (items[i].weight <= remaining) {
totalValue += items[i].value;
remaining -= items[i].weight;
} else {
totalValue += items[i].ratio * remaining;
break;
}
}
cout << "Maximum value in knapsack: " << totalValue << endl;
}
int main() {
int n, capacity;
cout << "Enter number of items: ";
cin >> n;
cout << "Enter knapsack capacity: ";
cin >> capacity;
Item* items = new Item[n];
cout << "Enter weight and value of each item:\n";
for (int i = 0; i < n; i++) {
int w, v;
cin >> w >> v;
items[i].set(w, v);
}
fractionalKnapsack(n, capacity, items);
delete[] items;
return 0;
}