金银岛 OpenJ_Bailian - 2795 (贪心)

https://vjudge.net/problem/OpenJ_Bailian-2795

贪心水题. 不解释

//金银岛 贪心
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 10010;
int w, s, k;
struct Metal{
    double nw; //性价比
    int v, n; //总重量和价值
}metal[maxn];
bool operator < (const Metal &a, const Metal &b)
{
    return a.nw<b.nw;
}

int main()
{
    scanf("%d",&k);
    while(k--){
        scanf("%d%d",&w,&s);
        memset(metal, 0, sizeof(metal));
        for(int i = 1; i <= s; i++){
            scanf("%d%d",&metal[i].n,&metal[i].v);
            metal[i].nw = (double)metal[i].v/metal[i].n; //分割
        }
        sort(metal+1, metal+s+1);
        double sum = 0;
        for(int i = s; i > 0; i--){
            if(w > metal[i].n) w-=metal[i].n, sum+=metal[i].v; //不拆分直接放完
            else{ //拆分
                sum += w*metal[i].nw;
                break;
            }
        }
        printf("%.2f\n",sum);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/a1097304791/article/details/83019196