51nod 1098 最小方差

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

题解:

求方差那个公式展开,因为最后还要乘以 m ,所以最开始的时候就不用乘以 m 了:

参考:http://blog.csdn.net/qingshui23/article/details/51834215

就可以写程序了, 我们就只需要找最小的s^2就行了;

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

typedef long long LL;
const LL maxn = 1e4+5;
const LL INF = 1e15+5;
LL a[maxn],sum[maxn],ans[maxn];

int main()
{
    int n,m;
    while(cin>>n>>m)
    {
        for(int i=1;i<=n;i++)
            scanf("%lld",&a[i]);
        sort(a+1,a+1+n);
        sum[0]=ans[0]=0;
        for(int i=1;i<=n;i++)
        {
            sum[i] = sum[i-1]+a[i];
            ans[i] = ans[i-1]+a[i]*a[i];
        }
        double MIN = (double)INF;
        for(int i=m;i<=n;i++)
        {
            double tmp = (ans[i]-ans[i-m])-1.0*(sum[i]-sum[i-m])*(sum[i]-sum[i-m])/m;
            if(tmp<MIN)
                MIN = tmp;
        }
         printf("%lld\n",(LL)MIN);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值