POJ 2833 求平均数。 模板:STL实现大根堆和小根堆

来源:互联网 发布:可变数据印刷软件价格 编辑:程序博客网 时间:2024/04/30 09:24

这题直接存储会超内存。因为n1,n2都很小,用大根堆和小根堆分别存储 最小的n2个数 和最大的n1个数。

//remove the greatest n1 ones and the least n2 ones//priority_queue <BIGR>   是大根堆//priority_queue <SMALLR> 是小根堆//priority_queue <int,vector<int>,less<int> >     大根堆//priority_queue <int,vector<int>,greater<int> >  小根堆#include <stdio.h>#include <algorithm>#include <queue>using namespace std;const int S=5000100;struct BIGR{    int n;    BIGR(int n=0):n(n){}    friend bool operator < (const BIGR &a , const BIGR &b){        return (a.n<b.n?1:0);    }};//restore the least n2 onesstruct SMALLR{    int n;    SMALLR(int n=0):n(n){}    friend bool operator < (const SMALLR &a , const SMALLR &b){        return (a.n<b.n?0:1);    }};int main(){    int n1,n2,n,i,j,k,tot,x;    double avg;    while (scanf("%d%d%d",&n1,&n2,&n),!(n1==0&&n2==0&&n==0)){        priority_queue <BIGR> small;        priority_queue <SMALLR> big;        tot=n-n1-n2;        avg=0;        for (i=0;i<n;i++)        {            scanf("%d",&x);            avg+=x*1.0/tot;            if (small.size()<n2){                small.push(x);            }            else{                if (x<small.top().n){                    small.pop();                    small.push(x);                }            }            if (big.size()<n1){                big.push(x);            }            else{                if (x>big.top().n){                    big.pop();                    big.push(x);                }            }        }        while (!small.empty()){            avg-=small.top().n*1.0/tot;//            printf("small: %d\n",small.top().n);            small.pop();        }        while (!big.empty()){            avg-=big.top().n*1.0/tot;//            printf("big: %d\n",big.top().n);            big.pop();        }        printf("%.6lf\n",avg);    }}


 

原创粉丝点击