首页 > 代码库 > hdu 4355 简单三分找最小值

hdu 4355 简单三分找最小值


#include<stdio.h>
#include<string.h>
#include<iostream>
#include<math.h>
using namespace std;
#define exp 1e-6

int n;
double pos[50010],weight[50010];
double min(double a,double b)
{
    return a<b?a:b;
}
double query(double x)
{
    int i;
    double sum=0;
    for(i=1;i<=n;i++)
    {
        double k=pos[i]-x;
        if(k<0) k=-k;
        sum+=k*k*k*weight[i];
    }
    return sum;
}
int main()
{
    int T,i,j,d=1;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        for(i=1;i<=n;i++)
        {
            scanf("%lf%lf",&pos[i],&weight[i]);
        }
        double left=pos[1];
        double right=pos[n];
        while(right-left>exp)
        {
            double mid=(2*left+right)/3;
            double mmid=(left+2*right)/3;
            if(query(mid)>query(mmid))
            {
                left=mid;
            }
            else right=mmid;
        }
        printf("Case #%d: %.0lf\n",d++,query(left));
    }
    return 0;
}

hdu 4355 简单三分找最小值