-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4sem_69.cpp
48 lines (39 loc) · 1.02 KB
/
4sem_69.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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Item {
int weight;
int value;
};
bool compareItems(const Item& a, const Item& b) {
return a.weight < b.weight;
}
double knapsack(int W, const vector<Item>& items) {
vector<Item> sortedItems = items;
sort(sortedItems.begin(), sortedItems.end(), compareItems);
double totalValue = 0.0;
for (const auto& item : sortedItems) {
if (W >= item.weight) {
totalValue += item.value;
W -= item.weight;
} else {
totalValue += (static_cast<double>(W) / item.weight) * item.value;
break;
}
}
return totalValue;
}
int main() {
vector<Item> items = {
{1, 15},
{2, 3},
{2, 2},
{3, 6},
{3, 8}
};
int capacity = 10;
double maxValue = knapsack(capacity, items);
cout << "Maximum value obtained from knapsack: " << maxValue << endl;
return 0;
}