2012 Multi-University Training Contest 6-1006 hdu4355 Party All the Time

来源:互联网 发布:在windows资源管理器 编辑:程序博客网 时间:2024/04/29 11:00

这个题就是求一个点p,使得(xp - xi ) ^ 3 (i = 1,2,..n)的和最小,通过大家总结这是一个单峰函数(具体是为什么我也不知道),通过三分法可以得到正解。

以下是一个很好的三分法的模板~~


#include <iostream>#include <cstdio>#include <cmath>#include <iomanip>using namespace std;typedef double D;const D eps = 1e-8;D x[50005];int n;D w[50005];D func(D y){    D temp = 0.0;    for(int i = 1;i <= n;i++)    {        if(x[i] < y)            temp += (y-x[i] )* (y-x[i] ) * (y-x[i] ) * w[i];        else if(x[i] > y)            temp += (x[i]-y)* (x[i]-y) * (x[i]-y) * w[i];    }    return temp;}D minn(D a,D b){    if(a < b) return a;    else return b;}D Ternary_Search(D lb, D rb){    D x1,x2;    while(fabs(1-lb/rb)>eps)    {        x1 = lb + (rb-lb)/3,x2 = rb-(rb-lb)/3;        if(func(x1)<func(x2))            rb = x2;        else lb = x1;    }    return func(lb);}int main(){    int t,cas =1;    scanf("%d",&t);    while(t--)    {        scanf("%d",&n);        for(int i = 1;i <= n;i++)        {            scanf("%lf%lf",&x[i],&w[i]);        }        D ans = Ternary_Search(x[1],x[n]);        printf("Case #%d: ",cas++);        cout <<fixed << setprecision(0)<< ans<< endl;    }    return 0;}


原创粉丝点击