Poj百练 4110:圣诞老人的礼物-Santa Clau’s Gifts (分类:贪心)

#include <iostream>
#include<cstdio>
#include<algorithm>
using namespace std;

const int maxn = 100+5;
int n, w;
struct Box{
    int v, w;
    double den;
};

bool operator < (const Box &a, const Box &b)    //重载比较
{
 return a.den>b.den;
}

int main()
{
    scanf("%d%d",&n,&w);
    Box boxes[maxn];
    for(int i = 1; i <= n; i++){
        scanf("%d%d",&boxes[i].v, &boxes[i].w);
        //直接计算出每个礼物的性价比
        boxes[i].den = 1.0*boxes[i].v/boxes[i].w;
    }

    //按升序进行排序
    sort(boxes+1, boxes+n+1);

    //按性价比从高到低依次向下取
    double totw = 0, totv = 0;
    for(int i = 1; i <= n; i++){
        if(w - totw >= boxes[i].w){ //可以放下
            totw += boxes[i].w;
            totv += boxes[i].v;
        }
        else{                       //放不下了
            totv += boxes[i].den*(w-totw);
            totw += w;
            break;
        }
    }

    printf("%.1lf",totv);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/a1097304791/article/details/81415969
今日推荐