mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-15 21:20:58 +00:00
build
This commit is contained in:
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user