poj 2010

优先队列

先将奶牛排序,考虑每个奶牛作为中位数时,比它分数低(前面的)的那群牛的学费总和left,后面的总和right。然后从分数高往分数低扫描,满足left + y + right <= F的第一个解就是最优解。

#include <iostream>
#include <queue>
#include <algorithm>
#include <cstring>

using namespace std;

const int MAXN = 100005;

struct P {
	int x;
	int y;
	int left;
	int right;
}e[MAXN];

bool cmp(P a, P b) {
	return a.x < b.x;
}

int main() {
	
	int n, c, f;
	memset(e, 0, sizeof(e));
	scanf("%d%d%d", &n, &c, &f);
	for(int i=1; i<=c; i++)
		scanf("%d%d", &e[i].x, &e[i].y);
	sort(e+1, e+c+1, cmp);
	if(n > 1) {
		priority_queue<int> que;
		int p, t, sum=0;
		for(int i=1; i<=n/2; i++) {
			p = e[i].y;
			que.push(p);
			sum += p;
		}
		for(int i=n/2+1; i<=c-n/2; i++) {
			e[i].left = sum;
			p = que.top();
			t = e[i].y;
			if(t < p) {
				que.pop();
				que.push(t);
				sum = sum - p + t;
			}
		}
		while(que.size())	que.pop();
		sum = 0;
		for(int i=c; i>c-n/2; i--) {
			p = e[i].y;
			que.push(p);
			sum += p;
		}
		for(int i=c-n/2; i>n/2; i--) {
			e[i].right = sum;
			p = que.top();
			t = e[i].y;
			if(t < p) {
				que.pop();
				que.push(t);
				sum = sum - p + t;
			}
		}
		int ans = -1;
		for(int i=c-n/2; i>n/2; i--) {
			int total = e[i].left + e[i].y + e[i].right;
			if(total <= f) {
				ans = e[i].x;
				break;
			}
		}
		printf("%d\n", ans);
	}
	
	return 0;
}


posted @ 2016-09-26 15:05  StevenLuke  阅读(153)  评论(0编辑  收藏  举报