POJ 3111 K Best (二分)

本文解决了一个从多个物品中选择特定数量的物品以使单位重量的价值最大的问题。通过使用二分查找算法并结合自定义比较器进行优化,最终实现了高效的求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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个物品的重量和价值分别是wi和vi。从中选取k个物品使得单位重量的价值最大,并输出物品的序号。

题解:

这种题直接贪心选取肯定是错的。应该用二分来做。

#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=1e5+5;
const double INF=1e6+5;
int v[maxn],w[maxn];
int n,k;
struct node
{
    double y;
    int id;
    bool operator < (const node &p) const//重载<运算符
    {
        return y>p.y;
    }
}a[maxn];
bool check(double x)//可以选择使得单位重量的价值不小于x
{
    for(int i=0;i<n;i++)
    {
        a[i].y=v[i]-x*w[i];
        a[i].id=i+1;
    }
    sort(a,a+n);
    double sum=0;
    for(int i=0;i<k;i++)
        sum+=a[i].y;
    return sum>=0;
}
void solve()
{
    double lb=0,ub=INF;
    for(int i=0;i<50;i++)
    {
        double mid=(lb+ub)/2;
        if(check(mid))
            lb=mid;
        else
            ub=mid;
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>k;
    for(int i=0;i<n;i++)
        cin>>v[i]>>w[i];
    solve();
    for(int i=0;i<k;i++)
        if(i)
            cout<<" "<<a[i].id;
        else
            cout<<a[i].id;
    cout<<endl;
    return 0;
}

转载于:https://www.cnblogs.com/orion7/p/7686271.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值