cpp-algo-cases/chapter_greedy/fractional_knapsack.cpp

57 lines
1.4 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: fractional_knapsack.cpp
* Created Time: 2023-07-20
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20><>Ʒ */
class Item {
public:
int w; // <20><>Ʒ<EFBFBD><C6B7><EFBFBD><EFBFBD>
int v; // <20><>Ʒ<EFBFBD><C6B7>ֵ
Item(int w, int v) : w(w), v(v) {
}
};
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>̰<EFBFBD><CCB0> */
double fractionalKnapsack(vector<int> &wgt, vector<int> &val, int cap) {
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ʒ<EFBFBD>б<EFBFBD><D0B1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ԣ<EFBFBD><D4A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֵ
vector<Item> items;
for (int i = 0; i < wgt.size(); i++) {
items.push_back(Item(wgt[i], val[i]));
}
// <20><><EFBFBD>յ<EFBFBD>λ<EFBFBD><CEBB>ֵ item.v / item.w <20>Ӹߵ<D3B8><DFB5>ͽ<EFBFBD><CDBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
sort(items.begin(), items.end(), [](Item &a, Item &b) { return (double)a.v / a.w > (double)b.v / b.w; });
// ѭ<><D1AD>̰<EFBFBD><CCB0>ѡ<EFBFBD><D1A1>
double res = 0;
for (auto &item : items) {
if (item.w <= cap) {
// <20><>ʣ<EFBFBD><CAA3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>򽫵<EFBFBD>ǰ<EFBFBD><C7B0>Ʒ<EFBFBD><C6B7><EFBFBD><EFBFBD>װ<EFBFBD><D7B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
res += item.v;
cap -= item.w;
} else {
// <20><>ʣ<EFBFBD><CAA3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>򽫵<EFBFBD>ǰ<EFBFBD><C7B0>Ʒ<EFBFBD><C6B7>һ<EFBFBD><D2BB><EFBFBD><EFBFBD>װ<EFBFBD><D7B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
res += (double)item.v / item.w * cap;
// <20><><EFBFBD><EFBFBD>ʣ<EFBFBD><CAA3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѭ<EFBFBD><D1AD>
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;
// ̰<><CCB0><EFBFBD>
double res = fractionalKnapsack(wgt, val, cap);
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ʒ<EFBFBD><EFBFBD>ֵΪ " << res << endl;
return 0;
}