code1 25分
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct yuebing {
double sale;
double store;
double price;
};
bool cmp(yuebing a, yuebing b) {return a.price > b.price;}
int main()
{
double kind, need,profit=0;
cin >> kind >> need;
vector<struct yuebing>v(kind);
for (int i = 0; i < kind; i++) cin >> v[i].store;
for (int i = 0; i < kind; i++) {
cin >> v[i].sale;
v[i].price = v[i].sale / v[i].store;
}
sort(v.begin(), v.end(),cmp);
for (int i = 0; i < v.size(); i++) {
if (v[i].store >= need) {
profit = profit + need * v[i].price;
break;
}
else {
profit = profit + v[i].sale;
need = need - v[i].store;
}
}
printf("%.2lf", profit);
return 0;
}
直接对结构体进排序
code2 25分
#include<iostream>
#include<map>
#include<vector>
using namespace std;
int main()
{
double kind,need,sale,profit=0;
cin >> kind >> need;
vector<double>store(kind);
map<double, double>m;
for (int i = 0; i < kind; i++) cin >> store[i];
for (int i = 0; i < kind; i++) {
cin >> sale;
m[sale / store[i]] += store[i];
}
for (auto it = m.rbegin(); it != m.rend(); it++) {
if (it->second <= need) {
profit += it->second*it->first;
need -= it->second;
}
else {
profit += need * it->first;
break;
}
}
printf("%.2lf", profit);
return 0;
}
在对象的启发下,对代码进行第二次优化。更加简洁
夸一下我的宝宝,真聪明