POJ 2833 The Average【优先队列】

版权声明:转载什么的好说,附上友链就ojek了,同为咸鱼,一起学习。 https://blog.csdn.net/sodacoco/article/details/86937622

新年第一题被优先队列教做人。

题目:

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 npositive 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 is.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 个最大的,求其余数的平均值;

解题思路:

        。

        用 sort ,wa了四发。

        要使用自动堆排序的优先队列,有一个有点绕的地方,使用优先队列维护最小堆和最大堆,如果选择最简单的堆来实现【比如我】,维护最大堆时需要存放 最初值的负数形式。

实现代码:

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
typedef long long ll;
ll n1,n2,n,sum;
priority_queue<ll> qmax,qmin;

void f(){
    for(int i=1;i<=n1;i++){
        sum+=qmax.top();
        qmax.pop();
    }
    for(int i=1;i<=n2;i++){
        sum-=qmin.top();
        qmin.pop();
    }
    printf("%.6f\n",(sum*1.0)/(n-n1-n2));
    return ;
}
int main(){
    while(scanf("%lld%lld%lld",&n1,&n2,&n)){
        sum=0;
        if(n1+n2+n==0) break;
        ll x;
        for(int i=1;i<=n;i++){
            scanf("%lld",&x);
            sum+=x;
            qmax.push(-x);
            if(qmax.size()>n1)qmax.pop();
            qmin.push(x);
            if(qmin.size()>n2)qmin.pop();
        }
        f();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sodacoco/article/details/86937622