hdu1009简单的贪心问题

来源:互联网 发布:使命召唤10 知乎 编辑:程序博客网 时间:2024/05/21 11:16

类似部分背包问题

按性价比排序

题目

#include <iostream>#include<algorithm>#include<cstdio>using namespace std;struct  food{    double j;    double f;    double w;};bool compare(food a,food b){    return a.w > b.w;}int main(){    int M,N,i;    food fo[1001];    double max;//    freopen("data.txt","r",stdin);//    freopen("out.txt","w",stdout);    while(cin>>M>>N ,!(M == -1 && N == -1))    {        max = 0;        for(i = 0 ; i < N; i++)        {            cin>>fo[i].j>>fo[i].f;            fo[i].w = fo[i].j / fo[i].f;        }        sort(fo,fo + N,compare);        for(i = 0 ;i < N;i++)        {                if(M * fo[i].w >= fo[i].j)                {                    M -= fo[i].f;                    max += fo[i].j;                }                else                {                    fo[i].j -= fo[i].w * M;                    max += fo[i].w * M;                    M = 0;                    break;                }        }        printf("%.3f\n",max);    }    return 0;}


0 0
原创粉丝点击