D - 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

题意:有N个珠宝,女主想保留下来K个,使得这K个珠宝的单位价值最高。

分析:实话实说,我一开始真的没想到这个题可以二分,感觉挺有意思拿出小本本记住。
对于每一个物品,我们需要得到它对所有物品的贡献,这样我们才能得到最优解。
显然,对于单个物品的平均价值进行排序是毫无意义的。所以通过二分单位贡献便可一步步逼近最优解的极限。

ps:重载运算符的效率高于cmp函数。

#include<iostream>
#include<cstring>
#include<iomanip>
#include<algorithm>
#include<cmath>
#include<cstdio>
using namespace std;
const int maxn = 1e6 + 10;
#define INF maxn
const double eps = 1e-8;
struct node {
    int v, w;
    int id;
    double t;
    bool operator <(const node &a) const
    {
        return t>a.t;
    }
}a[100010];
int N, K;
bool cmp(node a, node b)
{
    return a.t > b.t;
}
bool pty(node a, node b)
{
    return a.id < b.id;
}
int judge(double x)
{
    for (int i = 0; i < N; i++)
    {
        a[i].t = 1.0*a[i].v - x*a[i].w;
    }
    sort(a, a + N);
    double tmp = 0.0;
    for (int i = 0; i < K; i++)
    {
        tmp += a[i].t;
    }
    return (tmp >= 0) ? 1 : 0;
}
int main()
{
    while (scanf("%d%d", &N, &K) != EOF)
    {
        for (int i = 0; i < N; i++)
        {
            scanf("%d%d", &a[i].v, &a[i].w);
            a[i].id = i + 1;
        }
        double R = 1.0*INF;
        double L = 0.0;
        int k = 0;
        while (R - L > eps)
        {
            k++;
            double mid = (L + R) / 2;
            if (judge(mid))
            {
                L = mid;
            }
            else
                R = mid;
            if (k > 40)
                break;
        }
        sort(a, a + K, pty);
        for (int i = 0; i < K; i++)
        {
            if (i)
                printf(" ");
            printf("%d", a[i].id);
        }
        printf("\n");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值