Telecasting station - SGU 114(带劝中位数)

题目大意:在一个数轴上有N个点,每个点都有一个权值,在这个数轴上找一个点,是的每个点到这个点的距离之和乘上权值的总和最小。

分析:以前也遇到过类似的问题,不过并不知道这是带权值的中位数问题,百度百科有比较精彩的证明,可以证明出来跟这个位置和距离没有什么关系,只和权值有关系,假设这个点是T,那么 ∑d[L](L<T) + d[T] >= ∑d[R](R>=T+1),反之也成立。

 

代码如下:

=================================================================================================================

#include<stdio.h>
#include<algorithm>
#include<vector>
#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;

const int MAXN = 15007;

struct Point
{
    double x;
    int person;
}p[MAXN];

bool cmp(Point a, Point b)
{
    return a.x < b.x;
}

int main()
{
    int i, N, L=0, R=0;

    scanf("%d", &N);

    for(i=0; i<N; i++)
    {
        scanf("%lf%d", &p[i].x, &p[i].person);
        R += p[i].person;
    }

    sort(p, p+N, cmp);

    for(i=0; i<N; i++)
    {
        L += p[i].person;
        R -= p[i].person;

        if(L >= R)
            break;
    }

    printf("%lf\n", p[i].x);

    return 0;
}

 

posted @ 2015-09-17 11:08  无忧望月  阅读(134)  评论(0编辑  收藏  举报
levels of contents