有c個同學,每個同學有成績和助學金2個屬性,現在要你選出n個人,滿足他們的助學金之和小於等於f並且中位元盡量大。 我用了2個優先隊列,首先按照助學金從小到大排序,把前面的n個人放進優先隊列中,然後彈出前n/2個人,並且把n/2個人放進另外一個優先隊列中,這個優先隊列隊是最大堆,隊首是最大的助學金,然後從剩下的人開始枚舉,判斷是否成績大於第一個優先隊列隊首那個人的成績,如果是在判斷錢是否夠,如果滿足就需要替換,注意替換出來的那個人的助學金可能很低,如果比第二個優先隊列隊首那個人還要便宜,那就把他放到第二個優先隊列。 開始只開了一個隊列,錯了很多次,原因是前n/2個人只需要便宜即可,不需要成績有多好,所以枚舉的時候替換出來的那個人不能扔掉,因為前n/2個人可能成績比他低,但是比他貴,具體看代碼。
#include <cstdio>i#include <cstring>#include <queue>#include <algorithm>#include <vector>using namespace std;typedef long long LL;struct node{ int s, e;}a[110000];struct node2{ int x, y; node2() {} node2(int x, int y): x(x), y(y) {} bool operator < (const node2& rhs) const { if(x != rhs.x) return x > rhs.x; return y > rhs.y; }};bool cmp(node a, node b){ if(a.e != b.e) return a.e < b.e; return a.s > b.s;}int main(){ int n, m; LL f; while(scanf("%d %d %lld", &n, &m, &f) != EOF) { priority_queue<node2> Q; priority_queue<int> Q2; for(int i = 1; i <= m; i++) { scanf("%d %d", &a[i].s, &a[i].e); } sort(a+1, a+m+1, cmp); LL sum = 0; for(int i = 1; i <= n; i++) { sum += a[i].e; Q.push(node2(a[i].s, a[i].e)); } if(sum > f) { printf("-1\n"); } else { for(int i = 0; i < n/2; i++) { Q2.push(Q.top().y); Q.pop(); } for(int i = n+1; i <= m; i++) { int x = Q.top().x; int y = Q.top().y; if(x < a[i].s) { LL tmp = sum-y+a[i].e; if(Q2.top() > y) { tmp = tmp-(Q2.top()-y); Q2.pop(); Q2.push(y); } if(tmp <= f) { sum = tmp; Q.pop(); Q.push(node2(a[i].s, a[i].e)); } } } printf("%d\n", Q.top().x); } }}