准备天梯赛:
``
L2-003 月饼
`#include<bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
struct Nod
{
double kuchun, totalvalue, prevalue;
}yb[N];
bool cmp(const Nod &a, const Nod &b)
{
return a.prevalue > b.prevalue;
}
int main()
{
int n, d; cin >> n >> d;
for(int i = 1; i <= n; i++)
{
cin >> yb[i].kuchun;
}
for(int i = 1; i <= n; i++)
{
cin >> yb[i].totalvalue;
yb[i].prevalue = yb[i].totalvalue / yb[i].kuchun;
}
sort(yb + 1, yb + n + 1, cmp);
double ans = 0;
for (int i = 1; i <= n; i++)
{
if(d - yb[i].kuchun > 0)
{
ans += yb[i].totalvalue;
d -= yb[i].kuchun;
}
else
{
ans += d * yb[i].prevalue;
break;
}
}
printf("%.2f", ans);
return 0;
}`
考点:重写结构体比较函数。
有两种方式,重载比较运算符和申明cmp函数。
bool cmp(const Node &x,const Node &y){ if(x.a==y.a) return x.b<y.b; else return x.a<y.a; } sort(st,ed+1,cmp) //先比较a,a相同则比较b。这种方式运行较慢。
struct Node { int a, b; bool operator < (const Node& N) const { if(a == a.N) return b < N.b; else return a < N.a; } }; Node r[N]; //内嵌方式运行更快。
绘画:

浙公网安备 33010602011771号