Yougth现在有n个物品的重量和价值分别是Wi和Vi,你能帮他从中选出k个物品使得单位重量的价值最大吗?
3 2 2 2 5 3 2 1
0.75
思路:最后的结果肯定不大于每种物品的单价,我们只需要枚举从0到maxn之间的值就可以了。
代码:
#include <iostream> #include <algorithm> #include <cstring> #include <cmath> #include <cstdio> using namespace std; const int M = 1e4+10; const double e = 1e-3; struct node{ double w, v, rat; }s[M]; double y[M]; bool cmp(double a, double b){ return a > b; } bool judge(double x, int n, int k){ int i; for(i = 0; i < n; ++ i) y[i] = s[i].v- x*s[i].w; double sum = 0; sort(y, y+n, cmp); for(i = 0; i < k; ++ i) sum += y[i]; if(sum > 0) return 1; else return 0; } double bs(double l, double r, int n, int k){ double mid = (l+r)/2; int tem = 100; while(r - l > e){ if(judge(mid, n, k)){ l = mid; } else r = mid; mid = (l+r)/2; } return r; } int main(){ int n, k; while(scanf("%d%d", &n, &k) == 2){ int i; double maxn = 0; for(i = 0; i < n; ++ i){ scanf("%lf%lf", &s[i].w, &s[i].v); if(maxn < s[i].v/s[i].w) maxn = s[i].v/s[i].w; } double ans = bs(0, maxn, n, k); printf("%.2lf\n", ans); } return 0; }
原文地址:http://blog.csdn.net/shengweisong/article/details/44202101