Maximized average-Binary Search

Source: Internet
Author: User

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;}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.