Files
Data-Structure/Algorithm/Greedy/P2240 【深基12.例1】部分背包问题.cpp
2025-09-13 22:37:17 +08:00

47 lines
1.0 KiB
C++

#include <iostream>
#include <tuple>
#include <vector>
#include <iomanip>
#include <algorithm>
using namespace std;
struct cmp {
bool operator()(const tuple<double, double, double>& a,
const tuple<double, double, double>& b) const {
return get<2>(a) > get<2>(b); // 按性价比降序
}
};
int main() {
int n;
double t;
cin >> n >> t;
vector<tuple<double, double, double>> arr(n);
for (int i = 0; i < n; i++) {
double a, b;
cin >> a >> b;
arr[i] = make_tuple(a, b, b / a); // (重量, 价值, 单位价值)
}
sort(arr.begin(), arr.end(), cmp());
double value = 0;
int p = 0;
while (t > 0 && p < n) {
if (t >= get<0>(arr[p])) {
value += get<1>(arr[p]); // 取整个物品
t -= get<0>(arr[p]); // 先减当前重量
p++;
} else {
value += t * get<2>(arr[p]); // 取一部分
break;
}
}
cout << fixed << setprecision(2) << value << endl;
return 0;
}