http://acm.hdu.edu.cn/showproblem.php?pid=4355
Party All the Time
三分法求极值 模板
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
double s[50010], w[50010];
int n;
double Calc(double a)//所要计算的函数{
double ans= 0;
for( int i=0; i<n; i++)
ans+= fabs((s[i]- a)*(s[i]-a)*(s[i]-a))*w[i];
return ans;
}
double Solve()
{
double Left, Right;
double mid, midmid;
double mid_area, midmid_area;
Left = -1000000; Right = 1000000;
while (Left + 1e-8 < Right) //EPS为精度,搜寻范围left到right
{
mid = (Left + Right) / 2;
midmid = (mid + Right) / 2;
mid_area = Calc(mid);
midmid_area = Calc(midmid);
// 假设求解最大极值. //如果求最小极值下句判断改为<
if (mid_area < midmid_area) Right = midmid;
else Left = mid;
}
return mid;
}
int main(){
// freopen("1.txt", "r", stdin);
int T, i, j, k, text= 1;
scanf("%d", &T);
while( T--){
scanf("%d", &n);
for( i=0; i<n; i++){
scanf("%lf%lf", &s[i], &w[i]);
}
printf("Case #%d: %.0f\n", text++, Calc(Solve()));
}
return 0;
}