是一入门的好题目,也是一道神奇的题目
看来discus才知道G++是错的,C++是对的 -. - |||
题意:给出N个分数,要求去掉n1个最高分,n2个最低分,然后算平均分。
其实不太难,只是数据量太大,不能一次读入,但是可以看到,n1,n2都很小很小,只用全部加起来再减去n1个最大的数,减去n2个最小的数,于是,问题简化,球所有数的和,再减去即可,对于最大n1和最小n2求法,有了以下三种方法
1.用sort:
建立一个11的数组,然后high中全置零(任何分数大于0),low中全INF(任何分数小于INF),这样,当比high[n1]大的时候,就替换他,然后sort(……,cmp)一次,此时high[n1]又是最小的了,同理,计算low。
code:
#include <iostream>
#include <cstdio>
#include <algorithm>
#define INF 2000000000
using namespace std;
int high[14], low[14];
void init()
{
fill(high, high+14, 0);
fill(low, low+14, INF);
}
int cmp(int a, int b)
{
return a>b;
}
int main()
{
int n, great, least;
while(scanf("%d%d%d", &great, &least, &n), great&&least&&n)
{
__int64 sum=0;
int x;
init();
for(int i=0; i<n; i++)
{
scanf("%d", &x);
sum+=x;
if(x>high[great]){high[great]=x; sort(high, high+great+1, cmp);}
if(x<low[least]) {low[least]=x; sort(low, low+least+1);}
}
//for(int i=0; i<n; i++) cout<<high[i]<<" "<<low[i]<<endl;
for(int i=0; i<great; i++)
sum-=high[i];
for(int i=0; i<least; i++)
sum-=low[i];
printf("%.6lf\n", 1.0*sum/(n-great-least));
}
return 0;
}
2.异曲同工,用优先队列做,这个就不用自己定义数组和初始化什么的了
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
int main()
{
int great,least,n,i,x;
__int64 sum;
while (scanf("%d%d%d",&great,&least,&n), great && least && n)
{
priority_queue <int> q1; //从大到小出队
priority_queue <int,vector<int>,greater<int> > q2;
sum=0;
for (i=0;i<n;i++)
{
scanf("%d",&x);
sum+=x;
q2.push(x);
q1.push(x);
if(q1.size()>least)
q1.pop();
if(q2.size()>great)
q2.pop();
}
while(!q1.empty())
{
sum-=q1.top();
q1.pop();
}
while(!q2.empty())
{
sum-=q2.top();
q2.pop();
}
printf("%.6lf\n",1.0*sum/(n-great-least));
}
return 0;
}
3.用堆排序做可以,同优先队列思路类似
#include <iostream>
#include <cstdio>
#include <algorithm>
#define INF 2000000000
using namespace std;
int high[14], low[14];
void init()
{
fill(high, high+14, 0);
fill(low, low+14, INF);
}
int cmp(int a, int b)
{
return a>b;
}
int main()
{
int n, great, least;
while(scanf("%d%d%d", &great, &least, &n), great&&least&&n)
{
__int64 sum=0;
int x;
init();
for(int i=0; i<n; i++)
{
scanf("%d", &x);
sum+=x;
if(x>high[great])
{
high[great]=x;
make_heap(high,high+great+1,cmp);
pop_heap(high,high+great+1,cmp);
}
if(x<low[least])
{
low[least]=x;
make_heap(low, low+least+1);
pop_heap(low, low+least+1);
}
}
for(int i=0; i<great; i++)
sum-=high[i];
for(int i=0; i<least; i++)
sum-=low[i];
printf("%.6lf\n", 1.0*sum/(n-great-least));
}
return 0;
}
作者:FreeAquar
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。