二分三分 D POJ-3111 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 ≤ kn ≤ 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


n 个珍珠选k个使其s价值最大,如果每个都算s排序取前k个的话是不符合题意的,因为这无法保证总s价值最大,一开始想了好久没想过来,看了几篇题解才懂了。通过x(s)=v/w可得,y=x*w-v=0时,可得到最大s价值,所以我们可以二分x,计算每个的y并排序,即可得到答案。
#include <cstdio>
#include <algorithm>
using namespace std;

const double inf=99999999.0;
struct jew{
    long v;
    long w;
    int num;
    double y;
}j[100000];
int k,n;
double s;
const double eps=1e-8;

double cal(double x);
bool cmp(jew j1,jew j2);

int main()
{
    int i;
    double left,right,mid;

    scanf("%d%d",&n,&k);

    for(i=0;i<n;i++)
    {
        scanf("%d%d",&j[i].v,&j[i].w);
        j[i].num=i+1;
    }
    left=0;
    right=inf;    //注:左右取值
    while(left+eps<right){
        mid=(left+right)/2;
        if(cal(mid)>0)
            left=mid;
        else
            right=mid;
    }
    for(i=0;i<k-1;i++)
        printf("%d ",j[i].num);
    printf("%d\n",j[i].num);
}

double cal(double x)    二分x计算y
{
    int i;

    for(i=0;i<n;i++)
        j[i].y=j[i].v-x*j[i].w;
    sort(j,j+n,cmp);
    s=0;//!
    for(i=0;i<k;i++)
        s+=j[i].y;
    return s;
}

bool cmp(jew j1,jew j2)    //结构体排序比较函数
{
    return j1.y>j2.y;
}


猜你喜欢

转载自blog.csdn.net/daddy_hong/article/details/79234682