SGU114 水题 Easy Problem

题意:N个城市在坐标轴上,每个城市有坐标和人口。现设立一个广播站,每个城市的不满度是该城市人口与该城市到广播站距离的乘积。求广播站坐标使得各个城市不满度之和最小。

Problem: 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 citizens displeasure 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.

Sample Input
4
1 3
2 1
5 2
6 2

Sample Output
3.00000

解法:观察样例可以发现实际上2到5之间的每个点都是可行的。为什么呢?因为广播站前后人口相等!如果广播站前后人口不等,且广播站不在城市里,那么广播站可以往人多的一侧移动得到更优。如此一来得到结论,广播站一定设在城市里的!哪个城市?将城市按坐标排序,从左到右扫,累计人口,第一个使得当前累计人口超过总人口一半的城市就可以了!

Solution: From the sample, we can find that each point between 2 and 5 could be the place to build the station to satisfy the requirement. Why? Because the number of citizens before and after the station is equal! If it is not the case, and the station is not in a city, then the station can move to the side of more people to get a better result. So here comes a conclusion that the station must be set in a city! Which one? Sort the cities by coordinate, sum up the population one by one from left to right. The first city‘s coordinate that makes the current cumulative population larger than half of the total population is the answer!

#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
struct data {
       double pos;
       int s;
}a[16000];
int n,sum;
bool cmp(data a, data b) {
     if (a.pos<b.pos) return true;
     return false;
}
int main() {
    while (~scanf("%d",&n)) {
          sum = 0;
          for (int i=1;i<=n;i++) {
              scanf("%lf%d",&a[i].pos,&a[i].s);
              sum += a[i].s;
          }
          sort(a+1,a+n+1,cmp);
          sum = (sum+1)/2;
          int tt = 0;
          int i = 1;
          while (tt<sum) {
                tt += a[i].s;
                i++;
          }
          i--;
          printf("%.5lf\n",a[i].pos);
    }
    return 0;
}


SGU114 水题 Easy Problem

上一篇:C#入门经典学习笔记一


下一篇:MFC学习-第一课