poj3111 K Best 最大化平均值,二分

题目:http://poj.org/problem?id=3111

题意:给你n,k,n个数的v、w值,选出k个数,使得v之和/w之和最大化。

思路:一看到题目,这不是赤果果的贪心吗?为什么放在二分专题...然而v=5,w=10和v=1,w=2对结果的影响是不一样的。

甩个学习链接:https://blog.csdn.net/karry_zzj/article/details/70232097

附上代码:

#include<algorithm>
#include<stdio.h>
#include<iostream>
using namespace std;
const int maxn=1e6+10;
int n,k;
struct node
{
    int id;
    double v,w,y;
}p[maxn];
bool cmp(node a,node b)
{
    return a.y>b.y;
}
bool check(double mid)
{
    double tmp=0;
    for(int i=1;i<=n;i++)p[i].y=p[i].v-mid*p[i].w;
    sort(p+1,p+1+n,cmp);
    for(int i=1;i<=k;i++)
    {
        tmp+=p[i].y;
    }
    return tmp>=0;
}
int main()
{
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++)scanf("%lf%lf",&p[i].v,&p[i].w),p[i].id=i;
    double l=0,r=1e7,ans=0;
    while(r-l>1e-8)
    {
        double mid=(l+r)/2;
        if(check(mid))l=mid;
        else r=mid;
    }
    for(int i=1;i<=k;i++)
    {
        if(i==k)printf("%d\n",p[i].id);
        else printf("%d ",p[i].id);
    }
    return 0;
} 

猜你喜欢

转载自www.cnblogs.com/myrtle/p/11784366.html
今日推荐