错误答案,会丢失精度额
#include <bits/stdc++.h>
using namespace std;
struct Object {
float a, b;
float ratio;
} os[100005];
bool cmp(Object x, Object y) {
return x.ratio > y.ratio;
}
int N;
float M, ans = 0.0;
int main() {
cin >> N >> M;
for (int i = 0; i < N; i++) {
cin >> os[i].a >> os[i].b;
os[i].ratio = os[i].b / os[i].a;
}
sort(os, os + N, cmp);
for (int i = 0; i < N && M > 0; i++) {
if (M >= os[i].a) {
M -= os[i].a;
ans += os[i].b;
} else {
ans += os[i].ratio * M;
M = 0;
}
}
// Print the result with two decimal places
cout << fixed << setprecision(2) << ans << endl;
return 0;
}
呃呃,要改为double类型
#include <bits/stdc++.h>
using namespace std;
struct Object {
double a, b;
double ratio;
} os[100005];
bool cmp(Object x, Object y) {
return x.ratio > y.ratio;
}
int N;
double M, ans = 0.0;
int main() {
cin >> N >> M;
for (int i = 0; i < N; i++) {
cin >> os[i].a >> os[i].b;
os[i].ratio = os[i].b / os[i].a;
}
sort(os, os + N, cmp);
for (int i = 0; i < N && M > 0; i++) {
if (M >= os[i].a) {
M -= os[i].a;
ans += os[i].b;
} else {
ans += os[i].ratio * M;
M = 0;
}
}
// Print the result with two decimal places
cout << fixed << setprecision(2) << ans << endl;
return 0;
}