您的位置:首页 > 其它

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

2012-06-30 16:07 411 查看
这题直接存储会超内存。因为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 ones
struct 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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: