/
githubmirror
/
hello-algo
Обзор
Документация
Войти
/
githubmirror
/
hello-algo
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
en/codes/cpp/chapter_greedy/fractional_knapsack.cpp
56 строк
2 KB
Yudong Jin
Translate all code to English (#1836)
31 дек 2025, 02:44
Не верифицирован
31 дек 2025, 02:44
2778a6f
Код
Авторство
О чём код?
/** * File: fractional_knapsack.cpp * Created Time: 2023-07-20 * Author: krahets (krahets@163.com) */ #include "../utils/common.hpp" /* Item */ class Item { public: int w; // Item weight int v; // Item value Item(int w, int v) : w(w), v(v) { } }; /* Fractional knapsack: Greedy algorithm */ double fractionalKnapsack(vector<int> &wgt, vector<int> &val, int cap) { // Create item list with two attributes: 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 remaining capacity is sufficient, put the entire current item into the knapsack res += item.v; cap -= item.w; } else { // If remaining capacity is insufficient, put part of the current item into the knapsack res += (double)item.v / item.w * cap; // No remaining capacity, so break out of the loop break; } } return res; } /* Driver Code */ int main() { vector<int> wgt = {10, 20, 30, 40, 50}; vector<int> val = {50, 120, 150, 210, 240}; int cap = 50; // Greedy algorithm double res = fractionalKnapsack(wgt, val, cap); cout << "Maximum item value not exceeding knapsack capacity is " << res << endl; return 0; }