POJ2976: Dropping Tests 题解

本文介绍了一种解决01分数规划问题的有效方法。通过二分查找技术确定最优解,利用元素排序优化选择过程,确保所选元素组合的目标函数值最大。提供了完整的算法实现代码。

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

经典的01分数规划问题
01分数规划通常解决这样的问题
给定nn个元素,每个元素都有两个属性值ai,bibi,要选出其中的k个c1,c2...ckc1,c2...ck,最大化ki=1aciki=1bci∑i=1kaci∑i=1kbci
解决这样的问题我们可以考虑二分答案
假设当前二分出的答案是xx,我们考虑是否能选出k个元素满足条件
可以发现

i=1kacii=1kbcixi=1kacixi=1kbci0i=1k(acixbci)0

所以将所有元素按照aixbiai−xbi排序,取前kk个判sum是否大于0就好(这题中是前nkn−k个)

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <utility>
#include <cctype>
#include <algorithm>
#include <bitset>
#include <set>
#include <map>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <cmath>
#define LL long long
#define LB long double
#define x first
#define y second
#define Pair pair<int,int>
#define pb push_back
#define pf push_front
#define mp make_pair
#define LOWBIT(x) x & (-x)
#define DEBUG(...)
using namespace std;

const int MOD=1e9+7;
const LL LINF=2e16;
const int INF=2e9;
const int magic=348;
const double eps=1e-10;

inline int getint()
{
    char ch;int res;bool f;
    while (!isdigit(ch=getchar()) && ch!='-') {}
    if (ch=='-') f=false,res=0; else f=true,res=ch-'0';
    while (isdigit(ch=getchar())) res=res*10+ch-'0';
    return f?res:-res;
}

int n,k;
double l,r,mid;

struct node
{
    double a,b;
    inline bool operator < (const node &x) const {return a-mid*b>x.a-mid*x.b;}
}a[10048];

inline bool check()
{
    int i;
    sort(a+1,a+n+1);
    double A=0,B=0;
    for (i=1;i<=n-k;i++) A+=a[i].a,B+=a[i].b;
    if (A/B>=mid) return true; else return false;
}

int main ()
{
    int i;double ans;
    while (scanf("%d%d",&n,&k) && !(!n && !k))
    {
        for (i=1;i<=n;i++) a[i].a=getint();
        for (i=1;i<=n;i++) a[i].b=getint();
        l=0;r=1;ans=0;
        while (r-l>1e-6)
        {
            mid=(l+r)/2;
            if (check()) ans=mid,l=mid; else r=mid;
        }
        printf("%d\n",int(ans*100+0.5));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值