您的位置:首页 > 其它

POJ 3111 K Best(二分搜索,最大化平均值)

2015-12-04 21:45 417 查看
[align=center]K Best[/align]

Time Limit: 8000MS
Memory Limit: 65536K
Total Submissions: 7491
Accepted: 1936
Case 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 = {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


题意:有N颗珠宝,每颗珠宝的价值为vi,重量为wi。 女主不得已要卖掉部分珠宝,她想留下k颗珠宝,并要求(v1+v2+....vk)/(w1+w2+...wk)的值最大,输出女主留下的珠宝的编号。(可不按输入的顺序输出)。

题解:二分搜索,找出最大化的平均值,然后记录下每次被选中的珠宝编号,输出即可。

代码如下:

#include<cstdio>
#include<algorithm>
#define INF 1000100
using namespace std;
int n,k;
double v[100010],w[100010];

struct node
{
int id;
double y;
}num[100010];

int cmp(node a,node b)
{
return a.y>b.y;
}

bool dis(double x)
{
int i=0;
for(i=0;i<n;++i)
{
num[i].y=v[i]-x*w[i];
num[i].id=i+1;
}
sort(num,num+n,cmp);
double sum=0;//不小心把sum定义成了int,一直WA
for(i=0;i<k;++i)
sum+=num[i].y;
return sum>=0;
}

int main()
{
int i;
while(scanf("%d%d",&n,&k)!=EOF)
{
for(i=0;i<n;++i)
scanf("%lf%lf",&v[i],&w[i]);
double left=0,right=INF,mid;
while(right-left>1e-8)//100次超时,50次能过,30次不能过
{
mid=(left+right)/2;
if(dis(mid))
left=mid;
else
right=mid;
}
for(i=0;i<k-1;++i)
printf("%d ",num[i].id);
printf("%d\n",num[i].id);
}
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: