114. Telecasting station
Every city in Berland is situated on Ox axis. The government of the country decided to build new telecasting station. After many experiments Berland scientists came to a conclusion that in any city citizensdispleasure is equal to product of citizens amount in it by distance between city and TV-station. Find such point on Ox axis for station so that sum of displeasures of all cities is minimal.
Input
Input begins from line with integer positive number N (0<N<15000) – amount of cities in Berland. Following N pairs (X, P) describes cities (0<X, P<50000), where X is a coordinate of city and P is an amount of citizens. All numbers separated by whitespace(s).
Output
Write the best position for TV-station with accuracy 10-5.
Sample Input
4 1 3 2 1 5 2 6 2
Sample Output
3.00000题目大意:有一些城市坐落在x轴上,每个城市i都有一个人口数Pi。现在要在x轴上建一座电视塔,城市居民的烦恼值等于城市与电视塔的距离和城市人口的乘积,求一个电视塔的位置,使得所有城市的总烦恼值最小。
解题思路:三分法求极小值。(样例输出是3,自己写的程序跑出来是5,还以为自己错了,调试了半天。。。)
代码如下:
#include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#define EPS 1e-6
#define INF INT_MAX / 10
#define LL long long
#define MOD 100000000
#define PI acos(-1.0)
const int maxn = 15005;
struct city
{
int x;
int p;
};
city ct[maxn];
int n;
double cal(double dis)
{
double res = 0;
for(int i = 1;i <= n;i++){
res += fabs((double)ct[i].x - dis) * (double)ct[i].p;
}
return res;
}
int main()
{
scanf("%d",&n);
double lb,lm,um,ub = 0;
for(int i = 1;i <= n;i++){
scanf("%d %d",&ct[i].x,&ct[i].p);
if(ct[i].x > ub)
ub = ct[i].x;
}
lb = 0;
while(ub - lb > EPS){
lm = (lb + ub) / 2.0;
um = (lm + ub) / 2.0;
if(cal(lm) < cal(um))
ub = um;
else
lb = lm;
}
printf("%.5f\n",lb);
}