最大化平均值 - 二分搜索

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;
}

 

 

 

转载于:https://www.cnblogs.com/ccut-ry/p/7850938.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值