Question link: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 5073
Question: Give an online point, and then remove M from it to minimize the remaining distance to the center of gravity,
Because the center of gravity is equal to the average value of distance, the variance is minimized;
Analysis:
N-M points must be removed. We enumerate the starting position of this string from 1 to M,
It is then expanded by the formula of the sum of squares, and the sum of the squares of the first few items and the sum of the first few items can be preprocessed. The complexity is O (n );
The Code is as follows:
#include <iostream>#include <cstring>#include <algorithm>#include <cstdio>using namespace std;const int maxn = 50010;long long a[maxn];int main(){ int n,m,t; scanf("%d",&t); while(t--){ scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) scanf("%I64d",&a[i]); if(n==m){ printf("0\n"); continue; } sort(a+1,a+n+1); long long sum1=0,sum2=0; for(int i=1;i<=n-m;i++){ sum1+=a[i]; sum2+=a[i]*a[i]; } double mess = sum1*1.0/(n-m); double ans = sum2 + (n-m)*mess*mess - 2*sum1*mess; for(int i=1;i<=m;i++){ sum1 = sum1-a[i]+a[n-m+i]; sum2 = sum2 - a[i]*a[i]+a[n-m+i]*a[n-m+i]; mess = sum1*1.0/(n-m); ans = min(ans,sum2 + (n-m)*mess*mess - 2*sum1*mess); } printf("%.10lf\n",ans); } return 0;}/***1003 2-1 0 14 2-2 -1 1 2****/
ACM/icpm2014 Anshan field competition D Galaxy (HDU 5073)