https://www.patest.cn/contests/gplt/L2-003
题解:按平均值贪心。
坑:有一个样例卡住了,是因为
while (i<=n&&x - bs[i].num >= 0)
{i++}
形如这样的循环结构要防止bs越界(i++以后再次访问了bs[i])
#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <vector> #include <math.h> #include <string.h> #include <string> #include <map> #include<stack> #include<set> #include<string.h> #define pb push_back #define _for(i, a, b) for (int i = (a); i<(b); ++i) #define _rep(i, a, b) for (int i = (a); i <= (b); ++i) using namespace std; const int N = 10000 + 5; //double num[N], price[N], ave[N]; struct bing { float num, price, ave; }bs[N]; bool cmp(bing a, bing b) { return a.ave > b.ave; } int main() { int n; cin >> n; float x; cin >> x; for (int i = 1; i <= n; i++) { cin >> bs[i].num; } for (int i = 1; i <= n; i++) { cin >> bs[i].price; bs[i].ave = bs[i].price / bs[i].num; } sort(bs + 1, bs + 1 + n, cmp); float ans = 0; int i = 1; while (i<=n&&x - bs[i].num >= 0) { x -= bs[i].num; ans += bs[i].price; i++; } if(i<=n)ans += bs[i].ave*x; printf("%.2lf", ans); system("pause"); }