解题思路:k个物品单位重量的最大价值一定不会超过单个物品单位价值的最大值,且一定不小于0,这样我们就求出了最终答案所在的区间。然后利用二分压缩区间,直到求出最终结果。这道题目确实把二分法运用的很巧妙。。
AC:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 10005;
const double eps = 1e-4;
int n,k;
double w[maxn],v[maxn],x[maxn],max_ave;
bool judge(double a)
{
for(int i = 1; i <= n; i++)
x[i] = v[i] - a*w[i];
sort(x+1,x+1+n);
double sum = 0;
for(int i = 1; i <= k; i++)
sum += x[n-i+1];
if(sum >= 0) return true;
return false;
}
void binary_search()
{
double l = 0, r = max_ave, mid;
while(r - l > eps)
{
mid = (l + r) / 2;
if(judge(mid))
l = mid;
else r = mid;
}
printf("%.2lf\n",l);
}
int main()
{
while(scanf("%d%d",&n,&k)!=EOF)
{
max_ave = 0;
for(int i = 1; i <= n; i++)
{
scanf("%lf%lf",&w[i],&v[i]);
max_ave = max(max_ave,v[i]/w[i]);
}
binary_search();
}
return 0;
}