K BEST(最大化平均值)
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 = {i1, i2, …, 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 2
1 1
1 2
1 3
Sample Output
1 2
一.题解及分析
-
思路 : 对于这种最大化平均值类题目,应该利用v-w*s的和是否大于0来判断,然后二分s
-
注意:
-
不能用贪心分别算v/w,再排序
-
注意用结构体的时候排序时参数的形式,即sort的用法,但如果是结构体的话应该像以下这样排序,不然就报错(一定要加上struct)
bool cmp(struct book a,struct book b);//一定要加上struct,不然就报错 struct book { int v,w; double y; int index; } a[maxx]; bool cmp(struct book a,struct book b) { return a.y<b.y;//注意排序的对象 } sort(a+1,a+n+1,cmp);//sort函数的第三个参数表示 `````
-
AC代码:
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxx=1000005;
int k,n;
double L,R;
int f(double x);
bool cmp(struct book a,struct book b);//一定要加上struct,不然就报错
struct book
{
int v,w;
double y;
int index;
} a[maxx];
int main()
{
scanf("%d%d",&n,&k);
if(k==0)
{
printf("0");
return 0;
}
memset(a,0,sizeof(a));
for(int i=1;i<=n;i++)
{
scanf("%d%d",&a[i].v,&a[i].w);
a[i].index=i;
}
int count=0;
R=maxx;//一定不能写错了,如果这个写成R=0,L=maxx,就报错
L=0;
while(count<=50)
{
count++;
double mid=(L+R)/2 ;//注意是double型
if(f(mid)) L=mid;
else R=mid;
}
printf("%d",a[n].index);
for(int i=n-1;i>=n-k+1;i--)
printf(" %d",a[i].index);
return 0;
}
bool cmp(struct book a,struct book b)
{
return a.y<b.y;
}
int f(double x)
{
double sum=0;
for(int i=1;i<=n;i++)
{
a[i].y=a[i].v-x*a[i].w;
}
sort(a+1,a+n+1,cmp);
for(int i=n;i>=n-k+1;i--)
sum+=a[i].y;
if(sum>=0) return 1;
return 0;
}