思路:贪心
#include <iostream>
#include <algorithm>
#include <queue>
#include <iomanip>
using namespace std;
const int N = 1010;
double arrayK[N];
double arrayP[N];
struct cmp {
template <typename T>
bool operator() (const T& a, const T& b) {
if (a.second < b.second) return true; //不清楚排序,这个是从大到小
return false;
}
};
int main() {
int n; //n是月饼种类,cap是容量
double sum = 0, cap;
priority_queue<pair<double, double>, vector<pair<double,double>>, cmp> pq; //不清楚priority_queue如何默认比较大小
cin >> n >> cap;
int m = n;
int k = 0;
while (m --) { //输入总库存
double kc;
cin >> kc;
arrayK[k ++] = kc;
}
m = n;
k = 0;
while (m --) { //输入总售价
double price;
cin >> price;
arrayP[k ++] = price;
}
for (int i = 0; i < n; i ++) {
pq.emplace(arrayK[i], arrayP[i] / arrayK[i]);
}
while (cap > 0 && !pq.empty()) { //没有判断pq是否为空***
pair<double, double> moon = pq.top(); pq.pop();//pq忘了pop
if (cap - moon.first >= 0) {
sum += moon.first * moon.second;
}
else {
sum += cap * moon.second;
}
cap -= moon.first;
}
cout << fixed << setprecision(2) << sum << endl;
return 0;
}
错误点:
- cmp排序小于大于分不清
- 忘了判断优先队列为空的情况
- 每次取队顶时忘了pop