天天看點

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 ≤ i ≤ n) 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)));
	}
}
           
STL