poj 3111 K Best(二分)

来源:互联网 发布:空间电压矢量 知乎 编辑:程序博客网 时间:2024/05/29 09:14


K Best
Time Limit: 8000MS Memory Limit: 65536KTotal Submissions: 9341 Accepted: 2423Case Time Limit: 2000MS Special Judge

Description

Demy has n jewels. Each of her jewels has some value vi and weight wi.

Since her husband John got broke after recent financial crises, Demy has decided to sell some jewels. She has decided that she would keep k best jewels for herself. She decided to keep such jewels that their specific value is as large as possible. That is, denote the specific value of some set of jewels S = {i1i2, …, ik} as

.

Demy would like to select such k jewels that their specific value is maximal possible. Help her to do so.

Input

The first line of the input file contains n — the number of jewels Demy got, and k — the number of jewels she would like to keep (1 ≤ k ≤ n ≤ 100 000).

The following n lines contain two integer numbers each — vi and wi (0 ≤ vi ≤ 106, 1 ≤ wi ≤ 106, both the sum of all vi and the sum of all wi do not exceed 107).

Output

Output k numbers — the numbers of jewels Demy must keep. If there are several solutions, output any one.

Sample Input

3 21 11 21 3

Sample Output

1 2
平均值最大化问题


题意:有n个物品的重量和价值分别是wi和vi。从中选出k个物品使得单位重量的价值最大
也就是  k个物体的w相加除以k个物体的v相加最大

一般想到的是按单位价值对物品排序,然后贪心选取,但是这个方法是错误的,比如对nyoj的例题来说,从大到小地进行选取,输入的结果是5/7=0.714对于有样例不满足。
我们一般用二分搜索来做(其实这就是一个01分数规划)


我们定义:


条件 C(x) :=可以选k个物品使得单位重量的价值不小于x。


因此原问题转换成了求解满足条件C(x)的最大x。那么怎么判断C(x)是否满足?


变形:(sigma(v[i])/sigma(w[i]))>=x (i 属于我们选择的某个物品集合S)


进一步:sigma(v[i]-x*w[i])>=0


于是:条件满足等价于选最大的k个和不小于0.于是排序贪心选择可以判断,每次判断的复杂度是O(nlogn)。


#include <iostream>#include <cstdio>#include <algorithm>using namespace std;const int maxn = 100005;const double E = 1e-6;int n ,k,v[maxn],w[maxn];struct node{    int id;    double x;}a[maxn];int cmp(node a ,node b){    return a.x > b.x;}void bs(double l , double r){    while(r-l > E)              //以为除以肯定x(m)不一定是整数,所以用double    {        double m = (l+r)/2;        double ans = 0,ansl = 0;        for(int i = 1 ; i <= n;i++)        {            a[i].x = v[i] - m*w[i];            a[i].id = i;            //一定要有这个,因为原来那个顺序一直没变,变得只是一个临时数组a[i];所以用id记录他的位置,然后sort排序,让最大的前n个放前面        }        sort(a+1,a+1+n,cmp);        for(int i = 1; i <= k;i++)        {            ans += a[i].x;        }        if(ans >= 0)  {ansl = m; l = m;}        else  r = m;    }    return ;}int main(){    while(cin >> n >> k)    {        for(int i = 1; i <= n;i++)        {            cin >> v[i] >> w[i] ;        }        bs(0,maxn);        int flag = 0;        for(int i = 1; i <= k ; i++)         {            if(flag++)  cout << ' ';            cout << a[i].id;         }         cout << endl;    }    return 0;}


0 0