[题目]
In the Dark forest, there is a Fairy kingdom where all the spirits will go together and Celebrate the harvest every year. But there is one thing you may not know that they hate walking so much that they would prefer to stay at home if they need to walk a long way.According to our observation,a spirit weighing W will increase its unhappyness for S3*W units if it walks a distance of S kilometers.
Now give you every spirit's weight and location,find the best place to celebrate the harvest which make the sum of unhappyness of every spirit the least.
题目的大体意思是说森林里面有一些精灵,在一个坐标轴上。它们有两个属性:位置xi和重量wi。要寻找一个集合点,使得所有精灵的厌恶程度最小。每个精灵的厌恶程度=s^3*wi,其中s为精灵与集合点的距离。
[算法]
三分
[分析]
由凸函数的基本性质——几个凸函数的和仍然是凸函数 可以证明,最终的代价是关于位置的凸函数。求凸函数的极值可用三分的方法。
[注意]
三分的终止条件要特别注意。由于最后输出的是结果取整数,而结果是s的三次方。所以eps应为1e-4左右
[代码]
#include
#include
#include
#include
#include
using namespace std; #define MAXN 50100 #define EPS 0.1 double x[MAXN],w[MAXN]; int n,testcase; double calc(double s) { double ans=0; for (int i=1;i<=n;i++) ans+=fabs(x[i]-s)*fabs(x[i]-s)*fabs(x[i]-s)*w[i]; return ans; } double Sanfen(double left,double right) { while (right-left>EPS) { double ll=(left+(right-left)/3),rr=(ll+(right-left)/3); double llAns=calc(ll); double rrAns=calc(rr); if (llAns
right) right=x[i]; } double ans=Sanfen(left,right); ans=calc(ans); printf("Case #%d: %d\n",p,(int)(ans+0.5)); } }