This commit is contained in:
krahets
2024-05-06 14:40:36 +08:00
parent 7e7eb6047a
commit 5c7d2c7f17
54 changed files with 3456 additions and 215 deletions
@@ -73,9 +73,41 @@ We have created an `Item` class in order to sort the items by their unit value.
=== "C++"
```cpp title="fractional_knapsack.cpp"
[class]{Item}-[func]{}
/* Item */
class Item {
public:
int w; // Item weight
int v; // Item value
[class]{}-[func]{fractionalKnapsack}
Item(int w, int v) : w(w), v(v) {
}
};
/* Fractional knapsack: Greedy */
double fractionalKnapsack(vector<int> &wgt, vector<int> &val, int cap) {
// Create an item list, containing two properties: weight, value
vector<Item> items;
for (int i = 0; i < wgt.size(); i++) {
items.push_back(Item(wgt[i], val[i]));
}
// Sort by unit value item.v / item.w from high to low
sort(items.begin(), items.end(), [](Item &a, Item &b) { return (double)a.v / a.w > (double)b.v / b.w; });
// Loop for greedy selection
double res = 0;
for (auto &item : items) {
if (item.w <= cap) {
// If the remaining capacity is sufficient, put the entire item into the knapsack
res += item.v;
cap -= item.w;
} else {
// If the remaining capacity is insufficient, put part of the item into the knapsack
res += (double)item.v / item.w * cap;
// No remaining capacity left, thus break the loop
break;
}
}
return res;
}
```
=== "Java"