一、题目大意
给定N头牛的成绩和花费,从中取出C头牛(C为奇数),使得它们的花费不超过F同时中位数最大。
二、解题思路
对中位数的牛的下标进行二分,left选择为N的一半,right选择为所有牛的数量+1(二分算出的mid范围为[left+1,right-1])
对所有的牛按照分数排序
在判断函数里,首先校验下mid右边是否有N/2个元素,没有的话直接缩小mid,有的话把mid左边的牛和右边的牛的花费分别放入不同的优先队列。
从左右两边的队列中各拿出N/2个最小的(同时出队),与mid的花费求和,判断下是否小于等于F,如果小于等于F则是一个可行解,记录下,同时放大mid
如果大于F,用优先队列找出mid右边的剩余元素中花费最小的,用它代替mid判断是否可行,如果可行,证明mid这个位置取的比较偏,其实存在比mid分数更高的可行解,那就不断的二分去接近这个可行解,是可以达到的
如果优先队列右边没有剩余元素或者右边也找不到可行解,那么就缩小mid,直到找到可行的中位数
三、代码
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
struct Cow
{
ll cost, score;
Cow(ll cost = 0, ll score = 0) : cost(cost), score(score) {}
};
int N, C, halfN;
ll F;
Cow cows[100007];
bool compare(const Cow &a, const Cow &b)
{
return a.score < b.score;
}
void input()
{
scanf("%d%d%lld", &N, &C, &F);
halfN = N / 2;
for (int i = 1; i <= C; i++)
{
scanf("%lld%lld", &cows[i].score, &cows[i].cost);
}
sort(cows + 1, cows + 1 + C, compare);
cows[0].score = -1;
}
bool judge(int mid)
{
int countGt = C - mid;
if (countGt < halfN)
{
return false;
}
// 记录左边的钱
priority_queue<ll, vector<ll>, greater<ll>> leftQue;
// 记录右边的钱
priority_queue<ll, vector<ll>, greater<ll>> rightQue;
for (int i = 1; i < mid; i++)
{
leftQue.push(cows[i].cost);
}
for (int i = mid + 1; i <= C; i++)
{
rightQue.push(cows[i].cost);
}
ll leftSum = 0LL;
for (int i = 1; i <= halfN; i++)
{
leftSum += leftQue.top();
leftQue.pop();
}
ll rightSum = 0LL;
for (int i = 1; i <= halfN; i++)
{
rightSum += rightQue.top();
rightQue.pop();
}
ll sum = leftSum + rightSum + cows[mid].cost;
if (sum <= F)
{
return true;
}
if (!rightQue.empty())
{
sum = sum - cows[mid].cost + rightQue.top();
return sum <= F;
}
return false;
}
void binarySearch()
{
int left = halfN, right = C + 1;
int ans = -1;
while (left + 1 < right)
{
int mid = (left + right) / 2;
if (judge(mid))
{
ans = mid;
left = mid;
}
else
{
right = mid;
}
}
if (ans == -1)
{
printf("-1\n");
}
else
{
printf("%lld\n", cows[ans].score);
}
}
int main()
{
input();
binarySearch();
return 0;
}