Party All the Time
Time Limit : 6000/2000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 72 Accepted Submission(s) : 31
Problem Description
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 S[sup]3[/sup]*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.
Input
The first line of the input is the number T(T<=20), which is the number of cases followed. The first line of each case consists of one integer N(1<=N<=50000), indicating the number of spirits. Then comes N lines in the order that x[sub][i][/sub]<=x[sub][i+1][/sub] for all i(1<=i<n). div="" )<="" sub]<15="" 0<w[sub]i[="" sub]|<="10[sup]6[/sup]," |x[sub]i[="" (="" spirit.="" i-th="" the="" of="" weight="" and="" location="" representing="" sub],="" sub],w[sub]i[="" x[sub]i[="" :="" number="" real="" two="" contains="" line="">
Output
For each test case, please output a line which is "Case #X: Y", X means the number of the test case and Y means the minimum sum of unhappyness which is rounded to the nearest integer.
Sample Input
1 4 0.6 5 3.9 10 5.1 7 8.4 10
Sample Output
Case #1: 832
#include<stdio.h>
#include<string.h>
#include<cmath>
#include<queue>
#include<algorithm>
using namespace std;
int n;
struct node
{
double x1;
double w;
}str[50010];
double f(double x)
{
double sum,x1;
sum=0;
for(int i=0;i<n;i++)
{
x1=fabs(x-str[i].x1);
sum+=x1*x1*x1*str[i].w;
}
return sum;
}
double ternary_search(double L,double R) // 凸函数
{
double mid1,mid2;
if(L>R)swap(L,R);
while(R-L>1e-5)
{
mid1=(L+R)/2.0; // mid1=L+(R-L)/3;
mid2=(mid1+R)/2.0; // mid2=R-(R-L)/3;
if(f(mid1)>=f(mid2)) L=mid1;
else R=mid2;
}
return L;
}
int main()
{
int t,s;
scanf("%d",&t);
s=t;
while(t--)
{
double ans;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%lf%lf",&str[i].x1,&str[i].w);
ans=ternary_search(str[0].x1,str[n-1].x1);
ans=f(ans);
printf("Case #%d: ",s-t);
printf("%0.0lf\n",ans);
}
return 0;
}