51 nod 1098 最小方差

基准时间限制:1 秒 空间限制:131072 KB 分值: 20  难度:3级算法题
 收藏
 关注
若x1,x2,x3......xn的平均数为k。
则方差s^2 = 1/n * [(x1-k)^2+(x2-k)^2+.......+(xn-k)^2] 。
方差即偏离平方的均值,称为标准差或均方差,方差描述波动程度。
给出M个数,从中找出N个数,使这N个数方差最小。
Input
第1行:2个数M,N,(M > N, M <= 10000)
第2 - M + 1行:M个数的具体值(0 <= Xi <= 10000)
Output
输出最小方差 * N的整数部分。
Input示例
5 3
1
2
3
4
5
Output示例
2

#include <iostream>
#include <algorithm>
using namespace std;
using LL = long long;
int a[10005];
LL sum[10005];
LL sum2[10005];
int main()
{
	int n,i,m;
	cin>>n>>m;
	for(i=1; i<=n; ++i)
	{
		cin>>a[i];
	}
	sort(a+1,a+1+n);
	for(i=1; i<=n; ++i)
	{
		sum[i]=sum[i-1]+a[i]*a[i];
		sum2[i]=sum2[i-1]+a[i];
	}
	double min=1e15;
	for(i=m; i<=n; ++i)
	{
		double s=sum[i]-sum[i-m]-1.0*(sum2[i]-sum2[i-m])*(sum2[i]-sum2[i-m])/m;
		if(min>s)
		min=s;
	}
	cout<<(LL)min<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/rem_little_fan_boy/article/details/79935253
今日推荐