【优先队列/贪心】The Average

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 n1n2 and n (1 ≤ n1n2 ≤ 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个最小值,求剩下的平均数。

分析:维护两个优先队列,保证优先队列内有n1个最大值和n2个最小值,之后用总和减去两个优先队列的和然后除以剩余人数即可。

代码:

#include <iostream>
#include <cmath>
#include <algorithm>
#include <queue>
#include <functional>
#include <cstdio>
using namespace std;
typedef long long LL;
priority_queue<int, vector<int>, greater<int> >pque_max;//存大数
priority_queue<int>pque_min;//存小数

int main()
{
  int n1 = 0, n2 = 0, n = 0;
  while (cin >> n1 >> n2 >> n)
  {
    LL sum = 0;
    if (!n1 && !n2 && !n)
    {
      break;
    }
    int conut_top = 0, count_down = 0;
    for (int i = 0; i < n; i++)
    {
      LL temp = 0;
      scanf("%lld", &temp);
      sum += temp;
      //取最大的数
      if (conut_top < n1) 
      {
        pque_max.push(temp);
        conut_top++;
      }
      else {
        if (pque_max.top() < temp) 
        {
          pque_max.pop();
          pque_max.push(temp);
        }
      }
      //取最小的数
      if (count_down < n2)
      {
        pque_min.push(temp);
        count_down++;
      }
      else {
        if (pque_min.top() > temp)
        {
          pque_min.pop();
          pque_min.push(temp);
        }
      }
    }
    LL sub = 0;
    while (!pque_max.empty()) { sub += pque_max.top(); pque_max.pop(); }
    while (!pque_min.empty()) { sub += pque_min.top(); pque_min.pop(); }
    printf("%.6f\n", (((double)sum - sub) / double(n - n1 - n2)));

  }
  return 0;
}

 

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

4 × 1 =