二、stl ,模拟,贪心等 [Cloned] G - stl 的 优先队列

原题:

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.

题意:

给出一个数组,要求算出去掉前n1大的n1个数字和前n2小的n2个数字的平均值。

题解:优先队列用的不是很熟,wa了好几次才弄明白。

我是申请了两个优先数列,一个优先队列的队头为队列中最小的元素用来放最大的几个数,然后如果下一个数比这个队头要大,就把队头弹出把这个元素加进去,另外一个优先队列的队头为队列中最大的元素用来放最小的几个数。

然后用longlong型记录所有数据的和之后再减去两个队列中的所有元素,剩下的sum再除以剩下的元素数目就是平均数。

代码:AC

#include<cstdio>
#include<cstring>
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
priority_queue<int,vector<int>,greater<int> >minn;
priority_queue<int,vector<int>,less<int> >maxn;

int main()
{
	int n1,n2,n;
	while(cin>>n1>>n2>>n)
	{
		if(n1+n2+n==0)
			break;
		long long sum=0;
		int i,t;
		int maxnlog=0,minnlog=0;
		for(i=0;i<n;i++)
		{
			scanf("%d",&t);
			sum+=t;
		if(minnlog<n1)
		{
			minn.push(t);
			minnlog++;
		}
		else if(t>minn.top())
		{
			minn.pop();
			minn.push(t);
		}
		if(maxnlog<n2)
		{
			maxn.push(t);
			maxnlog++;
		}
		else if(t<maxn.top())
		{
			maxn.pop();
			maxn.push(t);
		}
		}
		while(!maxn.empty())
		{
			sum-=maxn.top();
			maxn.pop();
		}
		while(!minn.empty())
		{
			sum-=minn.top();
			minn.pop();
		}
		double m=(double)sum/(double)(n-n1-n2);
		printf("%f\n",m);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/npuyan/article/details/81369254
今日推荐