做题之前先看了三分。
二分就是求一个某个值,而三分适用于查找“极值”
先增后减
double three_devide(double l,double r)
{
double m1,m2;
while(r-l>=eps)//eps = 1e-6;
{
m1 = l + (r - l)/3;
m2 = r - (r - l)/3;
if(f(m1)<=f(m2))
l = m1;
else
r = m2;
}
return (m1+m2)/2;
}
先减后增
double three_devide(double l,double r)
{
double m1,m2;
while(r-l>=eps)//eps = 1e-6;
{
m1 = l + (r - l)/3;
m2 = r - (r - l)/3;
if(f(m1)<=f(m2))
l = m2;
else
r = m1;
}
return (m1+m2)/2;
}
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 3*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 [i]<=x [i+1] for all i(1<=i<N). The i-th line contains two real number : X i,W i, representing the location and the weight of the i-th spirit. ( |x i|<=10 6, 0<w i<15 )
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
题意:找到一个值使得小精灵的不舒适值最小。
解析:这个题的公式是 sum = ∑abs(x-x[i])^3 * w[i];
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstdio>
#include<vector>
#include<stack>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;
#define maxn 100005
#define eps 1e-6
struct node{
double x,w;
}s[maxn];
int t,n;
double fun(double x)
{
double sum = 0;
for(int i = 0; i < n; i ++)
{
double temp = abs(s[i].x - x);
sum += temp*temp*temp*s[i].w;
}
return sum;
}
int main()
{
scanf("%d",&t);
for(int i = 1; i <= t; i ++)
{
scanf("%d",&n);
for(int j = 0; j < n; j ++)
scanf("%lf %lf",&s[j].x,&s[j].w);
printf("Case #%d: ",i);
double l = s[0].x;
double r = s[n-1].x;
double m1,m2;
while(r-l>eps)
{
m1 = (l+r)/2;
m2 = (m1+r)/2;
if(fun(m1)-fun(m2)>eps)
{
l = m1;
}
else
{
r = m2;
}
}
printf("%.0f\n",fun(l));
}
}