优先队列
中位数
题意
奶牛学校招奶牛N只,要求总学费不超过F时,问奶牛测试分数的中位数最大为多少。总学费不够招N只奶牛时输出-1。
题解
用优先队列处理。先以分数排序,然后以第i只奶牛为中位数时,lower[i]表示比i分数低的奶牛它们学费总额的最小值;upper[i]表示比i分数高的奶牛它们学费总额的最小值(奶牛数量不够N/2只时为无穷大)。
时间复杂度主要在更新lower和upper上,为O(NlogN)
代码
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
const int MAXN = 100001;
const int INF = 100000000;
typedef pair<int,int> Pair;
int N, C, F;
Pair cows[MAXN];
int lower[MAXN];
int upper[MAXN];
int result = -1;
void solve()
{
int mid = N / 2;
{
int total = 0;
priority_queue<int> pq;
for(int i = 0; i < C; i++)
{
lower[i] = pq.size() == mid ? total : INF;
pq.push(cows[i].second);
total += cows[i].second;
if(pq.size() > mid)
{
total -= pq.top();
pq.pop();
}
}
}
{
int total = 0;
priority_queue<int> pq;
for(int i = C - 1; i >= 0; i--)
{
upper[i] = pq.size() == mid ? total : INF;
pq.push(cows[i].second);
total += cows[i].second;
if(pq.size() > mid) //size exceed, subtract maximun fee
{
total -= pq.top();
pq.pop();
}
}
}
for(int i = C - 1; i >= 0; i--)
{
if(cows[i].second + lower[i] + upper[i] <= F)
{
result = cows[i].first;
return ;
}
}
}
int main()
{
cin >> N >> C >> F;
for(int i = 0; i < C; i++)
cin >> cows[i].first >> cows[i].second;
sort(cows, cows + C);
solve();
cout<< result <<endl;
return 0;
}
超时代码,时间复杂度为O(N* N *logN),每次枚举中位数i的时候都重复计算i两边的最小费用。
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
const int MAXN = 100010;
typedef pair<int,int> Pair;
struct comp{
bool operator()(Pair a, Pair b)
{ return a.second > b.second; }
};
struct comp2{
bool operator()(Pair a, Pair b)
{ return a.first > b.first; }
};
priority_queue<Pair, vector<Pair>, comp > pq; // ascending of fee
int N, C, F;
Pair cows[MAXN];
int result = -1;
void solve()
{
int mid = N / 2;
for(int i = mid; i < C - mid; i++) //i means a cow as middle
{
int temp_fee = 0;
temp_fee += cows[i].second;
for(int j = 0; j < i; j++)
{
pq.push(cows[j]);
}
for(int j = 0; j < mid; j++)
{
temp_fee += pq.top().second;
pq.pop();
}
while(!pq.empty())
pq.pop();
for(int j = i + 1; j < C; j++)
{
pq.push(cows[j]);
}
for(int j = 0; j < mid; j++)
{
temp_fee += pq.top().second;
pq.pop();
}
while(!pq.empty())
pq.pop();
if(temp_fee <= F)
{
result = cows[i].first;
return;
}
}
}
int main()
{
cin >> N >> C >> F;
for(int i = 0; i < C; i++)
cin >> cows[i].first >> cows[i].second;
sort(cows, cows + C, comp2() ); //descending order of score
solve();
cout<< result <<endl;
return 0;
}