【二分】K Best POJ - 3111【珠宝平均值】【最大化平均值】

【二分】K Best POJ - 3111

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件,问如何取能够使平均价值最大,输出要取得珠宝的序号

思路:
二分平均价值得X,如果k件的平均价值大于X,则说明这样分可以,还可以取更大的平均价值。

-> ∑(下标k) vi / ∑(下标k) wi >X
-> ∑(下标k) vi > ∑(下标k) (wi * X)
->∑(下标k) (vi - wi * X) > 0
因此判断条件check为:遍历每一件珠宝,计算(vi - wi * X),取该值最大的K件珠宝,统计其和,如果该和大于0,说明可以,否则不行。

TIPS
这里要求输出的是珠宝的序号,因此要用结构体保存其序号

AC代码:

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <map>
#define INF 0x3f3f3f3f

using namespace std;

const int maxn = 100005;
int n, k;
struct node
{
    double sum;
    int v, w, num;
} ans[maxn];

bool cmp(node a, node b)
{
    return a.sum > b.sum;
}

bool c(double x)
{
    for(int i = 0; i < n; i++)
        ans[i].sum = ans[i].v - x * ans[i].w;
    sort(ans, ans + n, cmp);
    double sum = 0;
    for(int i = 0; i < k; i++)
        sum += ans[i].sum;
    if(sum >= 0)
        return true;
    else
        return false;
}

void sol()
{
    double l = 0, r = INF;
    for(int i = 0; i < 100; i++)
    {
        double mid = (r - l) / 2 + l;
        if(c(mid))
            l = mid;
        else
            r = mid;
    }
    for(int i = 0; i < k; i++)
    {
        if(i > 0) printf(" ");
        printf("%d", ans[i].num + 1);
    }
    printf("\n");
}

int main()
{
    while(~scanf("%d%d", &n, &k))
    {
        for(int i = 0; i < n; i++)
        {
            scanf("%d%d", &ans[i].v, &ans[i].w);
            ans[i].num = i;
        }
        sol();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/floraqiu/article/details/81209906
今日推荐