【Nowcoder】暑期多校day5 GPA (01分数规划)

版权声明:本文为博主原创文章,禁止所有形式的未经博主允许的转载行为。 https://blog.csdn.net/qq_33330876/article/details/81382867

题目大意

共有 n 个对象,每个对象有两个属性值 si ci,至多可以删去 k 个对象,求右式的最大值: i = 1 n s [ i ] c [ i ] i = 1 n s [ i ]


解题思路

01分数规划的经典问题。二分答案解决问题,当我们检查二分到的值 D 是否可以达到的时候,就需要判断是否存在一个方案使上式的值达到 D 。

i = 1 n s [ i ] c [ i ] i = 1 n s [ i ] D

i = 1 n s [ i ] c [ i ] i = 1 n s [ i ] D

i = 1 n s [ i ] ( c [ i ] D ) 0

这里的实现有一个技巧,可以用到 nth_element 函数取出前 k 小的元素,时间复杂度比直接 sort 要低。
(nth_element 函数把第 k 个元素放在应在的位置,然后把小于其的元素放在其前面,把大于其的元素放在它后面)


代码

#include <bits/stdc++.h>
using namespace std;

inline int read() {
    register int val=0, sign=1; char ch;
    while(~(ch=getchar()) && (ch<'0' || ch>'9') && ch!='-'); ch=='-'?sign=-1:val=ch-'0';
    while(~(ch=getchar()) && (ch>='0' && ch<='9')) val=(val<<1)+(val<<3)+ch-'0';
    return val*sign;
}

const int maxn=int(1e5)+111;
const double eps=1e-8;
int n,k;
double D;
struct Node {
    double s,c;
    Node() {}
    bool operator < (const Node &rhs) const {
        return s*(c-D)<rhs.s*(rhs.c-D);
    }
}p[maxn];

bool check(double v) {
    nth_element(p+1,p+k,p+1+n);
    register int i;
    double res=0;
    for(i=1;i<=n;++i) {
        if(i<=k && p[i].s*(p[i].c-D)<0) continue;
        res+=p[i].s*(p[i].c-D);
    }
    return res>=0;
}

void work() {
    n=read(), k=read();
    register int i;
    for(i=1;i<=n;++i) scanf("%lf",&p[i].s);
    for(i=1;i<=n;++i) scanf("%lf",&p[i].c);

    double l=0, r=1e8, mid=-1, res=-1;
    for(i=1;i<=200;++i) {
        mid=(l+r)*0.5;
        if(check(D=mid)) res=mid, l=mid+eps;
        else r=mid-eps;
    }
    printf("%.11lf\n",res);
    return;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
#endif
    work();

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_33330876/article/details/81382867
GPA