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:
题意:给出几颗行星的位置,你可以移动其中若干颗行星的位置,求移动后每个行星到整个星系中心的距离的平方和的最小值,行星的个数为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; }
相关文章推荐
- 【数学,方差运用,暴力求解】hdu-5037 Galaxy (2014鞍山现场)
- hdu 5073 Galaxy 2014 鞍山区域赛 数学
- Hdu 5037 Frog(2014 ACM/ICPC Asia Regional Beijing Online)[贪心 || 想法]
- 2014年北京区域赛 hdu 5037 贪心
- hdu 2014鞍山赛区 5073 Galaxy
- hdu 5078 Osu! (2014 acm 亚洲区域赛鞍山 I)
- hdu 5037 Galaxy 鞍山现场赛题目
- HDU 5073 Galaxy(2014鞍山赛区现场赛D题)
- hdu 5078 Osu! (2014 acm 亚洲区域赛鞍山 I)
- HDU 5037 FROG 贪心 2014北京网络赛F
- HDU 5073 Galaxy (2014 ACM/ICPC 鞍山赛区现场赛D题)
- HDU 5073 Galaxy(Anshan 2014)(数学推导,贪心)
- HDOJ Galaxy 5073【2014年鞍山区域赛D题-方差】
- hdu 5073 Galaxy(2014 鞍山现场赛)
- hdu 5071 Chat-----2014acm亚洲区域赛鞍山 B题
- ACM/ICPM2014鞍山现场赛D Galaxy (HDU 5073)
- hdu 5073 Galaxy(2014acm亚洲赛区鞍山 C)
- hdu 5073 Galaxy(2014acm亚洲赛区鞍山 D)
- HDU5073 ACM-ICPC亚洲区域赛鞍山赛区现场赛D题 Galaxy 贪心+数学推导
- hdu 5073 Galaxy /2014鞍山现场赛D题