Topic Links:
pid=5073 ">http://acm.hdu.edu.cn/showproblem.php?pid=5073
Test instructions: Given a line of points, and then can be removed from the M, so that the rest of the distance to the center of gravity is minimal,
Because the center of gravity equals the average distance. Therefore, the least variance is also obtained.
Analysis:
Since we have to remove m, there must be n-m, and we enumerate the starting position of this string from 1 to M,
It is then expanded by the square sum formula. Preprocess the first few squares. As well as the first few items and can, the complexity of 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 Live Race D Galaxy (HDU 5073)