51Nod1257(初学01分数规划)

来源:互联网 发布:我和僵尸有个约会知乎 编辑:程序博客网 时间:2024/06/05 18:38
基本的01分数规划问题
#include<cstdio>#include<algorithm>using namespace std;typedef long long ll;const int maxn = 50005;const double eps = 1e-9;ll gcd(ll x,ll y){return y ? gcd(y,x % y) : x;}struct node{    int w;    int p;    double val;    bool operator < (const node& T) const{        return val>T.val;    }}b[maxn];double mid;ll anss,ansx,tmps,tmpx;int n,k;bool check(){    int tot = 0;    for(int i=0;i<n;i++)        b[i].val = 1.0*b[i].p-b[i].w*mid;    sort(b,b+n);    double sum = 0;    tmps = 0; tmpx = 0;    for(int i=0;i<k;i++){        sum += b[i].val;        tmps += b[i].p;        tmpx += b[i].w;    }    if(sum-0>=eps) return true;    return false;}int main(){    scanf("%d%d",&n,&k);    for(int i=0;i<n;i++) scanf("%d%d",&b[i].w,&b[i].p);    double l = 0,r = 500000;    for(int i=0;i<100;i++)    {        mid = (l+r)/2;        if(check()) {            l = mid;            anss = tmps;            ansx = tmpx;        }        else r = mid;    }    ll tmp = gcd(anss,ansx);    anss/=tmp; ansx/=tmp;    printf("%lld/%lld\n",anss,ansx);    return 0;}

原创粉丝点击