The weight and value of n items are w [I] and v [I] respectively, and K items are selected to maximize the value of unit weight.
1 <= k <= n <= 10 ^ 4
1 <= w [I], v [I] <= 10 ^ 6
The general idea is to sort items by unit value, and then select items by greedy, but this method is incorrect and is not satisfied with the following example. We generally use binary search (in fact, this is a 01 score plan)
We define:
Condition C (x): = You can select k items so that the unit weight value is not less than x.
Therefore, the original problem is converted into the largest x that satisfies the condition C (x. So how can we determine whether C (x) meets the requirements?
Deformation: (sigma (v [I])/sigma (w [I])> = x (I belongs to a set of items we selected S)
Further: sigma (v [I]-x * w [I])> = 0
Therefore, condition fulfillment is equivalent to selecting the largest k and not less than 0. Therefore, the greedy sorting can be judged, and the complexity of each decision is O (nlogn ).
Code:
#include <iostream>#include <algorithm>#include <cstdio>using namespace std;const int maxn=1e4;const double eps=1e-5;int w[maxn],v[maxn],n,k;double y[maxn];bool check(double r){for(int i=0;i<n;i++){y[i]=v[i]-r*w[i];}sort(y,y+n);reverse(y,y+n);double sum=0;for(int i=0;i<k;i++){sum+=y[i];}return sum>=0;} int main(){while(cin>>n){cin>>k;for(int i=0;i<n;i++)cin>>w[i]>>v[i];double lb=0,ub=1e6;while(ub-lb>eps){double mid=(lb+ub)/2;if(check(mid)) lb=mid;else ub=mid;}printf("%.2f\n",ub); }return 0;}