最大化平均值 - 二分搜索

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最大化平均值 - 二分搜索相关的知识,希望对你有一定的参考价值。

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
Sample Output
1 2


题意 : 从 n 个物品中选出 k 个,问怎么选平均总价值最大 ?

思路 :

  先取前k个元素算出S0 =∑(vi/wi) 作为初始值 ,然后对每一个元素(n个)求s=vi-x*wi

  要体会二分搜索过程的关键点,二分的 mid 值就是你所要一直求得值。

代码 :

 

const int eps = 1e5+5;
const double pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
#define Max(a,b) a>b?a:b
#define Min(a,b) a>b?b:a
#define ll long long

int n, k;
struct node
{
    int v, w, pt;
    double s;
    
    bool operator< (const node& ff)const{
        return s > ff.s;
    }
}pre[eps];

bool check(double x){
    for(int i = 1; i <= n; i++){
        pre[i].s = 1.0*pre[i].v - x*pre[i].w;
    }    
    sort(pre+1, pre+n+1);
    double sum = 0;
    for(int i = 1; i <= k; i++){
        sum += pre[i].s;
    }
    return sum >= 0;
}

int main() {
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", sttout);
    
    while(~scanf("%d%d", &n, &k)){
        for(int i = 1; i <= n; i++){
            pre[i].pt = i;
            scanf("%d%d", &pre[i].v, &pre[i].w);
        }
        double l = 0, r = 1.0*inf;
        
        for(int i = 1; i <= 200; i++){
            double mid = (l + r) / 2.0;
            if (check(mid)) l = mid;
            else r = mid;
        }
        
        for(int i = 1; i < k; i++){
            printf("%d ", pre[i].pt);
        }
        printf("%d\n", pre[k].pt);
        //printf("%.2f\n", ans);
    }
    return 0;
}

 

 

 







以上是关于最大化平均值 - 二分搜索的主要内容,如果未能解决你的问题,请参考以下文章

K Best(最大化平均数)_二分搜索

POJ 2976 3111(二分-最大化平均值)

POJ 3111 K Best 二分 最大化平均值

POJ 2018 Best Cow Fences(二分最大区间平均数)题解

最大化平均值

二分法 最大化平均值