[hdu4355]Party All the Time(三分)
解题关键:三分法裸题,一开始一定要保证函数为凸函数或者凹函数。
#include<bits/stdc++.h> #define eps 1e-6 using namespace std; int n; double x[50010],w[50010]; double fuc(double a){//用pow会超时 double d,ans=0; for(int i=1;i<=n;i++){ d=fabs(x[i]-a); ans+=d*d*d*w[i]; } return ans; } double sanfen(){ double m1,m2,l=-1e6+0.0,r=1e6+0.0; while(r-l>eps){ m1=(l+r)/2; m2=(m1+r)/2; if(fuc(m1)<fuc(m2))r=m2; else l=m1; } return r; } int main(){ int t,tt=1; scanf("%d",&t); while(t--){ scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%lf%lf",x+i,w+i); double ans=sanfen(); if(n==1) printf("Case #%d: %.0f\n",tt++,0.0); else printf("Case #%d: %.0f\n",tt++,fuc(ans)); } return 0; }