sgu 114

带权中位数的应用。
给定位置数组x[0...n]和权重数组w[0...n]
求 x 使得 w0|x0 - x| + w1|x1 - x| + ... + wn|xn - x|最小

#include <cstdio>
#include <vector>
#include <cmath>
#include <cassert>
#include <algorithm>
using namespace std;

struct City {
    double x;
    int p;
};

struct CmpByX {
bool operator() (const City &a, const City &b) const {
   return a.x < b.x;
}} cmpByX;


vector<City> a;

void run() {
    int N;
    scanf("%d", &N);
    a.resize(N);
    int i;
    double x; int p;
    int total = 0;
    for (i = 0; i < N; ++i) {
        scanf("%lf %d", &x, &p);
        a[i].x = x;
        a[i].p = p;
        total = total + p;
    }

    sort(a.begin(), a.end(), cmpByX);
    int sum = 0;
    for (i = 0; i < a.size(); ++i) {
        sum = sum + a[i].p;
        if (sum * 2 >= total)
            break;
    }

    printf("%.5lf\n", a[i].x);
}


int main() {
    run();
    return 0;
}


你可能感兴趣的:(sgu 114)