POJ 2833 优先队列+思维

http://poj.org/problem?id=2833

In a speech contest, when a contestant finishes his speech, the judges will then grade his performance. The staff remove the highest grade and the lowest grade and compute the average of the rest as the contestant’s final grade. This is an easy problem because usually there are only several judges.

Let’s consider a generalized form of the problem above. Given n positive integers, remove the greatest n1 ones and the least n2 ones, and compute the average of the rest.

Input

The input consists of several test cases. Each test case consists two lines. The first line contains three integers n1, n2 and n (1 ≤ n1, n2 ≤ 10, n1 + n2 < n ≤ 5,000,000) separate by a single space. The second line contains n positive integers ai (1 ≤ ai ≤ 108 for all i s.t. 1 ≤ in) separated by a single space. The last test case is followed by three zeroes.

Output

For each test case, output the average rounded to six digits after decimal point in a separate line.

Sample Input

1 2 5
1 2 3 4 5
4 2 10
2121187 902 485 531 843 582 652 926 220 155
0 0 0

Sample Output

3.500000
562.500000

Hint

This problem has very large input data. scanf and printf are recommended for C++ I/O.

The memory limit might not allow you to store everything in the memory.

题目大意:给你n个数字,删去最大的n1个和最小的n2个,然后计算剩下的数的平均值。

思路:用优先队列。Hint已经说了,空间不够存储所有的数字的。自己算也可以知道,n最大是5*10^6,那么空间大小就是:4*5*10^6/1024,约等于2wk,而题目只给了1wk的空间,所以我们考虑用两个优先队列,一个存储最大的n1个值,另外一个存储最小的n2个值,再用总和减去这两个就可以计算平均值了。优先队列元素默认是从大到小排列的,这种情况下存储的反而是n2最小值,因为你每次的pop操作去除的都是最大的元素,那剩下的自然是最小的。另外一个我们构建成最小堆,使用priority_queue<int,vector<int>,greater<int> > 即可。(容器默认是vector<int> 比较函数默认是 less<int>)这个最小堆用来存储最大的n1个元素。(这题一开始想了很多别的方法,卡了很久才想起来可以这么做,思维还是太局限了。)

#include<iostream>
#include<cstdio>
#include<stack>
#include<cmath>
#include<cstring>
#include<queue>
#include<map>
#include<set>
#include<algorithm>
#include<iterator>
#define INF 0x3f3f3f3f
typedef long long ll;
typedef unsigned long long ull;
using namespace std;

int main()
{
	int n1,n2,n;
	while(~scanf("%d%d%d",&n1,&n2,&n)&&(n1||n2||n))
	{
		int temp;
		priority_queue<int> q1;	//大根堆
		priority_queue<int,vector<int>,greater<int> > q2;	//小根堆
		double sum=0;
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&temp);
			sum+=temp;
			q1.push(temp);
			q2.push(temp);
			if(q1.size()>n2)
				q1.pop();
			if(q2.size()>n1)
				q2.pop();
		}
		while(!q1.empty())
		{
			sum-=q1.top();
			q1.pop();
		}
		while(!q2.empty())
		{
			sum-=q2.top();
			q2.pop();
		}
		printf("%.6f\n",sum/(1.0*(n-n1-n2)));
	}
}

猜你喜欢

转载自blog.csdn.net/xiji333/article/details/86660919