POJ3111--K Best

题目大意:Demy要卖掉珠宝,每样珠宝有两个属性,价值v和重量w。自己留k件,使得k件的价值和除以k件的重量和最大,也就是单位重量的价值最大


分析:和POJ2976一个道理,传送门http://blog.csdn.net/hhhhhhj123/article/details/47865473。另外,这题精度有点高。


代码:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

#define eps 1e-7
const int maxn = 111111;

int n, k;
double x;

struct J{
    int a, b;
    int id;
    bool operator <(const J & cmp) const {
        return a-x*b > cmp.a-x*cmp.b;
    }
}j[maxn];

bool C(double mid) {
    x = mid;
    sort(j, j+n);
    double tota = 0.0, totb = 0.0;
    for(int i = 0; i < k; i++) {
        tota += j[i].a;
        totb += j[i].b;
    }
    return tota/totb > mid;
}

int main() {
    while(~scanf("%d%d", &n, &k)) {
        double mx = 0.0;
        for(int i = 0; i < n; i++) {
            scanf("%d%d", &j[i].a, &j[i].b);
            mx = max(mx, j[i].a*1.0/j[i].b);
            j[i].id = i+1;
        }
        double L = 0.0, R = mx;
        while(fabs(R-L) > eps) {
            double mid = (L+R)/2;
            if(C(mid)) L = mid;
            else R = mid;
        }
        for(int i = 0; i < k; i++)
            printf("%d%c", j[i].id, i == k-1 ?  '\n' : ' ');
    }
    return 0;
}


你可能感兴趣的:(POJ3111--K Best)