Question:
On the number axis, there are N points. Each point has a weight of 1. K of them can be moved to any position. The Chinese sub-value di represents the distance between the I-th point and the center of gravity of the current N points.
Ideas:
In the formula, wi can be removed. If all the values are 1, the formula is changed to I = min (sum (di * di ))
Consider moving the K points directly to the center of gravity so that Di is 0.
It is easy to think that we should move K points from the two sides to the middle after sorting all the points, and then some continuous points are left, so we can enumerate the remaining continuous intervals.
In this case, we convert I = min (sum (di * di ))
= Min (sum (Li-mi) * (Li-mi) (Li is the center of gravity of the I point MI)
= Min (sum (LI * Li)-2 * mi * sum (LI) + Mi * mi * (n-k ))
In this way, we can use the prefix and to maintain the answer and combine the enumerated complexity above, that is, O (n)
Code:
#include<cstdio>#include<iostream>#include<cstring>#include<string>#include<algorithm>#include<map>#include<set>#include<vector>#include<queue>#include<cstdlib>#include<ctime>#include<cmath>#include<bitset>using namespace std;typedef long long LL;#define M 50010#define mod 1000000007int T, n, k;double s[M], s2[M];double ans;int main() { int i, j; double tmp, mid; scanf("%d", &T); while (T--) { scanf("%d%d", &n, &k); for (i = 1; i <= n; i++) scanf("%lf", &s[i]); ans = 0; if (n != k) { sort(s + 1, s + n + 1); for (i = 1; i <= n; i++) s2[i] = s[i] * s[i]; double sum1 = 0, sum2 = 0; for (i = 1; i <= n - k; i++) { sum1 += s[i]; sum2 += s2[i]; } mid = sum1 / (n - k); ans = sum2 - 2.0 * mid * sum1 + mid * mid * (n - k); for (i = 2, j = n - k + 1; j <= n; i++, j++) { sum1 -= s[i - 1]; sum1 += s[j]; sum2 -= s2[i - 1]; sum2 += s2[j]; mid = sum1 / (n - k); tmp = sum2 - 2.0 * mid * sum1 + mid * mid * (n - k); if (tmp < ans) ans = tmp; } } printf("%.10f\n", ans); } return 0;}
HDU 5073 galaxy