您的位置:首页 > 其它

hdu 5037 Galaxy 2014鞍山区域赛D(最小方差 贪心 想法)

2014-10-30 21:31 281 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5073

题意:给出几颗行星的位置,你可以移动其中若干颗行星的位置,求移动后每个行星到整个星系中心的距离的平方和的最小值,行星的个数为n,可移动的个数为k

思路:

贪心思路 1. 将k颗行星都移到其他n-k颗行星的中心,则这k颗的距离都为零,原问题简化成了从n颗中取出n-k颗,使其平方和最小.

贪心思路 2. 根据观察发现了,中心的坐标其实就是所有坐标的平均值,所以原问题其实就是求一个数列的方差的最小值,由于方差描述了一个串数的波动情况,所以所取的n-k个数一定要是连续的,才能使其方差最小。

数学推导: 设n个数为x1,x2,x3,,,,,,,xn,其平均值为xx,所以有

(x1-xx)^2+(x2-xx)^2+(x3-xx)^2+,,,,,+(xn-xx)^2=(x1^2+x2^2+,,,,,,+xn^2)-2*xx*(x1+x2+...+xn)+n*xx*xx

所以我们维护一个和,再维护一个平方和就能快速的计算出一段序列的方差。 其复杂度为O(n) 排序复杂度为O(nlogn)。

要注意n==k的情况,这个时候会除零。

code:

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

const int maxn=55000;

double a[maxn];

int main()
{
int T,n,k,cnt;
double sum1,sum2,ans,xx;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&k);
for(int i=0;i<n;i++) scanf("%lf",&a[i]);
sort(a,a+n);
xx=ans=sum1=sum2=0;
cnt=n-k;
if(!cnt){
printf("0\n");
continue;
}
for(int i=0;i<cnt;i++){
sum1+=a[i];
sum2+=a[i]*a[i];
}
xx=sum1/cnt;
ans=sum2-2*xx*(sum1)+cnt*xx*xx;
for(int i=cnt;i<n;i++){
sum1-=a[i-cnt];
sum2-=a[i-cnt]*a[i-cnt];
sum1+=a[i];
sum2+=a[i]*a[i];
xx=sum1/cnt;
ans=min(ans,sum2-2*xx*sum1+cnt*xx*xx);
}
printf("%f\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: