SGU 114 Telecasting station(二分)

来源:互联网 发布:淘宝绫致时装官方店 编辑:程序博客网 时间:2024/05/22 06:46

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 (XP) 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

41 32 15 26 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);}


0 0
原创粉丝点击