K Best(最大化平均数)_二分搜索

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

K Best(最大化平均数)_二分搜索.

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 2
1 1
1 2
1 3

Sample Output

1 2

【题意】有n个物品的重量和价值分别是w[i]和v[i],从中选出K个物品使得单位重量的价值最大。

1<=k<=n<=10^5

1<=w[i],v[i]<=10^7

【思路】一般想到的是按单位价值对物品排序,然后贪心选取,但是这个方法是错误的,对于有样例不满足。

我们一般用二分搜索来做(其实这就是一个01分数规划)

我们定义:

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

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

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

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

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

参考链接:http://www.2cto.com/kf/201308/235786.html

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int inf=0x3f3f3f3f;
const int N=;
struct node
{
double w,v,ret;
int id;
}a[N];
int n,k;
bool cmp(node a,node b)
{
return a.ret>b.ret;
}
bool ok(double mid)//是否满足条件SUM(v[i]-x*w[i])>=0
{
double sum=;
for(int i=;i<=n;i++)
{
a[i].ret=a[i].v-mid*a[i].w;
}
sort(a+,a++n,cmp);
for(int i=;i<=k;i++)
{
sum+=a[i].ret;
}
return sum>=;
}
int main()
{
while(~scanf("%d%d",&n,&k))
{
for(int i=;i<=n;i++)
{
scanf("%lf%lf",&a[i].v,&a[i].w);
a[i].id=i;
}
double l=,r=1.0*inf;
while(r-l>1e-)//二分搜索
{
double mid=(l+r)/;
if(ok(mid))
l=mid;
else r=mid;
}
for(int i=;i<k;i++)
{
printf("%d ",a[i].id);
}
printf("%d\n",a[k].id); }
return ;
}
上一篇:Python之路Day18-正则及Django


下一篇:Sql Server 优化 SQL 查询:如何写出高性能SQL语句