将每个学生先按照分数排序,再以每个学生作为中间点,在优先队列的帮助下分别找到在比这名学生前面和后面援助金额之和最少的(n-1)/2名学生,在数组lower和upper中记录金额。
总金额为该学生的援助金与他前后n-1个学生的援助金之和。
遍历所有解的时候需要从大往小遍历(元素越多,固定为n个元素之和才有可能越小),第一个满足总金额小于等于基金的即为最优解。
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
const int INF = 2*10e9+5;
const int MC = 10e5;
typedef pair<int, int> P;
priority_queue<int> q;
P stu[MC+5];
int lower[MC+5];
int upper[MC+5];
int main()
{
int n, c, f;
scanf("%d%d%d", &n, &c, &f);
for (int i = 0; i < c; i++) {
scanf("%d%d", &stu[i].first, &stu[i].second);
}
sort(stu, stu + c);
int fund = 0;
for (int i = 0; i < c; i++) {
lower[i] = (q.size() == (n-1)/2) ? fund : INF;
fund += stu[i].second;
q.push(stu[i].second);
if (q.size() > (n-1)/2) {
fund -= q.top();
q.pop();
}
}
while (!q.empty()) {
q.pop();
}
fund = 0;
for (int i = c - 1; i >= 0; i--) {
upper[i] = (q.size() == (n-1)/2) ? fund : INF;
fund += stu[i].second;
q.push(stu[i].second);
if (q.size() > (n-1)/2) {
fund -= q.top();
q.pop();
}
}
int ans = -1;
for (int i = c - (n-1)/2 - 1; i >= (n-1)/2; i--) {
if (lower[i] + stu[i].second + upper[i] <= f) {
ans = stu[i].first;
break;
}
}
printf("%d\n", ans);
return 0;
}