http://acm.hdu.edu.cn/showproblem.php?pid=4355
题意: 坐标轴上有一些点,每个点有权值,找出一个位置,所有点到这个点的距离的三次方乘以权值的和最小。
用三分求解就可以了
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
const double EPS = 1e-4;
const int MAXN = 50000+100;
int n, T;
double a[MAXN];
double b[MAXN];
double maxlen(double t) {
double ans = 0;
for(int i = 0; i < n; ++i){
ans += (a[i]-t)*(a[i]-t)*((fabs)(a[i]-t))*b[i];
}
return ans;
}
int main() {
scanf("%d", &T);
for(int t = 1; t <= T; ++t) {
scanf("%d", &n);
for(int i = 0; i < n; ++i) {
scanf("%lf %lf",&a[i],&b[i]);
}
double l = -1e6 , r = 1e6;
while(l + EPS < r) {
double m1 = l + (r - l) / 3;
double m2 = r - (r - l) / 3;
if(maxlen(m1) < maxlen(m2)) r = m2;
else l = m1;
}
printf("Case #%d: %.0lf\n", t, maxlen(l));
}
return 0;
}